10.18 — 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 (.):

struct Person
{
    int age{};
    double weight{};
};

Person person{};

// Member selection using actual struct variable
person.age = 5;

This syntax also works for references:

struct Person
{
    int age{};
    double weight{};
};
Person person{}; // define a person

// Member selection using reference to struct
Person& ref{ person };
ref.age = 5;

However, with a pointer, you need to use the arrow operator:

struct Person
{
    int age{};
    double weight{};
};
Person person{};

// Member selection using pointer to struct
Person* ptr{ &person };
ptr->age = 5;

The arrow operator does the same as an indirection followed by the . member selection operator

(*ptr).age = 5;
// same as
ptr->age = 5;

Note that indirection through the pointer must be enclosed in parentheses, because the member selection operator has a higher precedence than the indirection operator.

The arrow operator is not only easier to type, but is also much less prone to error because the indirection 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.

Best practice

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

The member selection operator is always applied to the currently selected variable. If you have a mix of pointer- and normal member variables, you can see member selections where . and -> are mixed.

#include <iostream>
#include <string>

struct Paw
{
    int claws{};
};
 
struct Animal
{
    std::string name{};
    Paw paw{};
};
 
int main()
{
    Animal puma{ "Puma", { 5 } };
 
    Animal* pointy{ &puma };
 
    // pointy is a pointer, use ->
    // paw is not a pointer, use .
    std::cout << pointy->paw.claws << '\n';
 
    return 0;
}
guest
Your email address will not be displayed
Avatars from https://gravatar.com/ are connected to your provided email address.
Notify me about replies:  
54 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments