Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Pointer->Call() and (*Pointer).Call() [duplicate]

Possible Duplicate:
ptr->hello(); /* VERSUS */ (*ptr).hello();

I am learning C++ and my question is if there is any difference between using the arrow operator (->) or dereferencing the pointer * for calling a function.

These two cases illustrate my question.

Class* pointer = new Class();
(*pointer).Function();         // case one
pointer->Function();           // case two

What is the difference?

like image 242
danijar Avatar asked Jun 24 '26 02:06

danijar


2 Answers

If the operators * and -> aren't overloaded, both versions accomplish the same.

like image 184
Olaf Dietsche Avatar answered Jun 26 '26 15:06

Olaf Dietsche


Given

Class* pointer = new Class();

Then

(*pointer).Function();         // case one

dereferences the pointer, and calls the member function Function on the referred to object. It does not use any overloaded operator. Operators can't be overloaded on raw pointer or built-in type arguments.

pointer->Function();           // case two

This does the same as the first one, using the built-in -> because pointer is a raw pointer, but this syntax is better suited for longer chains of dereferencing.

Consider e.g.

(*(*(*p).pSomething).pSomethingElse).foo()

versus

p->pSomething->pSomethingElse->foo()

The -> notation is also more obvious at a glance.

like image 28
Cheers and hth. - Alf Avatar answered Jun 26 '26 17:06

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!