What is the difference between the dot (.) operator and -> in C++? [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.

Solution 4:

The arrow operator is like dot, except it dereferences a pointer first. foo.bar() calls method bar() on object foo, foo->bar calls method bar on the object pointed to by pointer foo.

Solution 5:

The . operator is for direct member access.

object.Field

The arrow dereferences a pointer so you can access the object/memory it is pointing to

pClass->Field