"foo->bar()" versus "(*foo).bar()" [duplicate]
What is the difference between the dot (.) operator and -> in C++?
Solution 1:
foo->bar()
is the same as (*foo).bar()
.
The parenthesizes above are necessary because of the binding strength of the *
and .
operators.
*foo.bar()
wouldn't work because Dot (.
) operator is evaluated first (see operator precedence)
The Dot (.
) operator can't be overloaded, arrow (->
) operator can be overloaded.
The Dot (.
) operator can't be applied to pointers.
Also see: What is the arrow operator (->) synonym for in C++?
Solution 2:
For a pointer, we could just use
*pointervariable.foo
But the .
operator has greater precedence than the *
operator, so .
is evaluated first. So we need to force this with parenthesis:
(*pointervariable).foo
But typing the ()'s all the time is hard, so they developed ->
as a shortcut to say the same thing. If you are accessing a property of an object or object reference, use .
If you are accessing a property of an object through a pointer, use ->
Solution 3:
Dot operator can't be overloaded, arrow operator can be overloaded. Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). Dot operator can't be applied to pointers.
EDIT
When applied to pointer arrow operator is equivalent to applying dot operator to pointee e.g. ptr->field
is equivalent to (*ptr).field
.