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?
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.
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.
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.
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.
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
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.
Yes. ptr->method()
is two characters shorter than (*ptr).method()
.
It is also prettier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With