Search

6.12 — Member selection with pointers and references

It is common to have either a pointer or a reference to a struct (or class). As you learned previously, you can select the member of a struct using the member selection operator (.):

This syntax also works for references:

However, with a pointer, you need to dereference the pointer first:

Note that the pointer dereference must be enclosed in parenthesis, because the member selection operator has a higher precedence than the dereference operator.

Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. The following two lines are equivalent:

This is not only easier to type, but is also much less prone to error because the dereference is implicitly done for you, so there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator instead of the . operator.

Rule: When using a pointer to access the value of a member, use operator-> instead of operator. (the . operator)

6.12a -- For-each loops
Index
6.11 -- Reference variables

23 comments to 6.12 — Member selection with pointers and references

  • Vishal Singhal

    What cannot be done using references in C++. Can we have array of references just like array of pointers?

    • Alex

      There are a few things you can’t do with references (this is not an exhaustive list):

      * You can’t dynamically allocate memory using references.
      * You can’t have a null reference.
      * You can’t change where a reference points (they’re implicitly const).
      * You can’t have a pointer to a reference (because a reference isn’t considered a real object in C++).
      * You can’t have an array of references (because an array is essentially a pointer, and you can’t have a pointer to a reference).

      I’m sure there are others.

  • dice3000

    Brain overflow. Need to take a rest 🙂

  • zmotaghi67@gmail.com

    i love you Alex.
    every time i stuck and want to understand some thing deeply,i just come here… and i am sure i will get what i want.
    you must write all those heavy books.
    not these stupids called writers that just make things hazier!

  • Paulo Henrique

    • Arduino_User

      This is covered in lesson 6.10.

      Basically, you say that the pointer points to a constant address, NOT that it points to a constant value. The following lines are OK:


      const int *constPointer = &value; // fine!

      The value of the pointer cannot be changed; but the pointer can be assigned to another address. Or:


      const int *const constPointer = &value; // Also fine!

      Here, you cannot change the value of the pointer OR the address it points to.

  • Rob G.

    Hi Alex I have 2 questions. In the code below dereference occurs as a step if the -> is not used. What does the dereferencing produce? Literally what value/object is a result of dereferencing.  (full code at bottom)
    1)

    I’ve lost my way. What does the & do in this line?
    2)

    Full code:

    • Alex

      1) (*n_ptr).value_1 = 5; is the same as n_ptr->value_1 = 5;, so you’re just assigning the value of 5 to the value_1 member of mem_vars.
      2) In this context, & gets the address of mem_vars, so the pointer can point to it. Remember that pointers hold addresses.

  • Rob G.

    Thank you Alex, clear as always.

  • Shiva

    Alex,

    Isn’t the -> operator called the arrow operator? And the . operator called the dot operator? Since you didn’t mention them I was wondering if they were colloquial names. Then, in the last sentence:

    > … always use operator-> instead of operator.
                                                                       ^ dot operator or full stop? 😀

    IMHO you should at least say "… always use the -> operator instead of the . operator." if you’re not using the terminology. Put the symbol before ‘operator’.

    That last sentence also deserves a rule status, doesn’t it? Repeat in italics! 🙂

    • Alex

      . is often called “dot” and -> is often called “arrow”, but these are colloquial names. I’ve updated the article based on your other suggestions. Thanks!

  • Maxwell

    Thank you for everything Alex.  You have brought me from total noobiness to the point where I can output dynamically allocated 2d arrays of chars in the console.  I have recommended your tutorials to a friend and look forward to reading more.

  • J3ANP3T3R

    so like … pointers hold memory address only and to get the value of a memory address that the pointer is pointing to you add * before the pointer variable.

    but can anyone explain why ptr->age = 5; ?

    i mean it seems like ptr now is a reference to the value of the memory address. it has become what data type the memory address is holding. why is it not *ptr->age = 5; ?

  • Raghu

    Alex loving your tutorial! thank for everything

  • Rob G.

    Hi Alex

    regarding

    is &ref an alias for object test?
    Is &ref referencing the address of test?
    for e.g. [code]A * ptr = new A()

    , deleting is done by deleting the pointer? ptr
    for Object object, object.a (etc.), how is it destroyed? Delete only works on the heap

    Reviewing some here.

    • Alex

      In Test &ref = test, ref is an alias for object test.
      For A *ptr = new A(), you delete this by simply calling “delete ptr”. We’ll talk about what happens when objects are deleted (e.g. destructors) in chapter 8. And yes, delete only works with dynamically allocated memory, which means it only works on the heap.

  • Rob G.

    Gosh hate to post yet another question on this one chapter but, here goes: why is C++ configured so that we use aliases often. Why do we use aliases instead of original values? What function does the alias serve?

    • Alex

      If by “aliases” you mean references, we use (const) references wherever we can because they prevent values from being needlessly copied (especially when transferring an argument to a function parameter).

      • Rob G.

        I understand that -- you have some really good teaching pts. there. What tripped me up was the insistence of some to call references aliases. I need to disambiguate: e.g.

        "When a reference is created, you must tell it which variable it will become an alias for."

        "A reference variable is an alias, that is, another name for an already existing variable."

        These are from "teaching sites".

        So naturally I thought maybe I missed a teaching point.

  • Rob G.

    Ok, thx for putting this together for me: using (.) operator and (->) selection operator on the object…

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter