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