views:

644

answers:

6

i was learning about c++ pointers... so 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?

+28  A: 

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

dsimcha
Spot on and interesting, I didn't know that was how D worked. Why is it thought that the term syntactic sugar irritates the hell out of me? :D
xan
PITA - "Pain In the Ass" ?
shoosh
@shoosh: you got it.
Ken Bloom
+5  A: 

They generate the same exact machine code, but for me, ptr->arg() is much easier to read than (*ptr).arg().

Andrei Krotkov
+6  A: 

The only reason to have the '->' operator is to make it more convenient and save errors like:

*ptr.hello();

Because it is so easy to forget the parenthesis.

jjnguy
A: 

These alternate syntax modes are adopted from C, and you might get some additional understanding from A Tutorial on Pointers and Arrays in C, specifically, chapter 5, Pointers and Structure.

Don Wakefield
+7  A: 

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.

Colin
+14  A: 

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.

Max Lybbert
Of course, anyone overriding in such a way to make those operations behave differently does deserve to be shot.
Paul Smith
`operator->()` is pretty much limited invoking methods on some substitute object (i.e. making smart pointer classes of your own)unary `operator*()` is overloaded all the time for iterators (which are essentially the same thing), but it's also usefully overloaded in PCFG parsing such as boost::spirit to indicate the kleene star.
Ken Bloom