Reputation: 4683
So say I have an object/pointer/whatever the definition of such a thing is:
A* a = new A();
who happens to have methods
b();
c();
The way of doing things that I've found out is this:
a->b();
and the method worked very well. However now I have seen people doing it this way:
(*a).b();
The question is: What is the difference (i.e. how are addresses and values managed in each) between these two ways of calling methods and according to that, which is best one to use?
If this a duplicate of other question, just let me know, I will erase it after I see the original question.
Upvotes: 1
Views: 136
Reputation: 168626
For pointers, there is no difference:
If you declare:
A* pointer_to_A = new A();
Then these two are equivalent by definition:
pointer_to_A->b();
(*pointer_to_A).b();
If, however, you declare on object:
A a;
Then these two are not necessarily equivalent:
a->b();
(*a).b();
In this case, the first line invokes A::operator->()
while the second invokes A::operator*()
. (Aside: this case is somewhat rare. It is most often used for objects that behave like pointers: iterators, smart points and such. If they are well-designed, then the two forms above are still identical.)
Upvotes: 2
Reputation: 53037
There is no difference. Prefer ->
as it is cleaner and states what you mean better.
However, ->
and *
can be overloaded. So for certain classes they may do different things, although this is very very uncommon, and impossible for pointers.
Upvotes: 0