Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ptr->hello(); /* VERSUS */ (*ptr).hello();

I was learning about C++ pointers and the -> operator seemed strange to me. Instead of ptr->hello(); one could write (*ptr).hello(); because it also seems to work, so I thought the former is just a more convenient way.

Is that the case or is there any difference?

like image 424
Joey Avatar asked Jan 15 '09 16:01

Joey


3 Answers

The -> operator is just syntactic sugar because (*ptr).hello() is a PITA to type. In terms of the instructions generated at the ASM level, there's no difference. In fact, in some languages (D comes to mind), the compiler figures everything out based on type. If you do ptr.hello(), it just works, because the compiler knows that ptr is a pointer and doesn't have a hello() property, so you must mean (*ptr).hello().

like image 139
dsimcha Avatar answered Nov 10 '22 12:11

dsimcha


Others have already answered regarding built-in pointers. With regards to classes, it is possible to overload operator->(), operator&(), and operator*() but not operator.().

Which means that an object may act differently depending on which syntax you call.

like image 38
Max Lybbert Avatar answered Nov 10 '22 13:11

Max Lybbert


The main advantage in terms of readability comes when you have to chain function calls, i.e.:

ptr->getAnotherPtr()->getAThirdPtr()->print()

I'm not even going to bother doing this with the * operator.

like image 8
Paul Avatar answered Nov 10 '22 11:11

Paul