Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer dereference operator ( (*) vs -> )

Is there a general difference between doing

(*ptr).method()

vs

ptr->method()

I saw this question in a comment on another question and thought I would ask it here. Although I just remembered that pretty much every operator in C++ can be overloaded, so I guess the answer will depend. But in general, is there a difference between doing one versus the other?

like image 529
Falmarri Avatar asked Nov 24 '10 05:11

Falmarri


People also ask

What does the dereference operator (*) do?

In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value.

How is * used to dereference pointers?

Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.

What is the difference between <- and -> operator?

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 -> is called the arrow operator. It is formed by using the minus sign followed by a greater than sign. Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.


3 Answers

As "jamesdlin" already noted, the * and -> operators can be overloaded for class types.

And then the two expressions (*ptr).method() and ptr->method() can have different effect.

However, for the built-in operators the two expressions are equivalent.

The -> operator is more convenient when you're following a chain of pointers, because . has higher precedence than *, thus requiring a lot of ungrokkable parentheses.

Consider:

pBook->author->snailMail->zip 

versus

(*(*(*pBook).author).snailMail).zip 
like image 193
Cheers and hth. - Alf Avatar answered Sep 21 '22 19:09

Cheers and hth. - Alf


For raw pointer types, they are the equivalent.

And yes, for general types, the answer is indeed "it depends", as classes might overload operator* and operator-> to have different behaviors.

like image 26
jamesdlin Avatar answered Sep 20 '22 19:09

jamesdlin


Yes. ptr->method() is two characters shorter than (*ptr).method().

It is also prettier.

like image 23
wrongusername Avatar answered Sep 17 '22 19:09

wrongusername