Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the dot (.) operator and -> in C++? [duplicate]

Tags:

c++

operators

What is the difference between the dot (.) operator and -> in C++?

like image 988
moorthy Avatar asked Aug 06 '09 12:08

moorthy


People also ask

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.

What is the -> operator in C?

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.

What is the difference between * and -> in C++?

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).

What is the difference between two member access operators and ->?

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.


2 Answers

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++?

like image 180
SwDevMan81 Avatar answered Oct 17 '22 16:10

SwDevMan81


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 ->

like image 26
Gordon Gustafson Avatar answered Oct 17 '22 18:10

Gordon Gustafson