What is the difference between the dot (.) operator and -> in C++?
Difference between Dot(.)operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers.
The dot ( . ) operator is used to access a member of a struct, while the arrow operator ( -> ) in C is used to access a member of a struct which is referenced by the pointer in question.
if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).
Remarks. The member access operators . and -> are used to refer to members of struct , union , and class types. Member access expressions have the value and type of the selected member.
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++?
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 ->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With