2

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?

Community
  • 1
  • 1
danijar
  • 32,406
  • 45
  • 166
  • 297
  • 3
    Thanks, I noticed that my question is a duplicate of http://stackoverflow.com/questions/447543/ptr-hello-versus-ptr-hello and http://stackoverflow.com/questions/7681926/c-pointers-difference-between-and?rq=1. I am sorry. – danijar Nov 19 '12 at 13:51

2 Answers2

6

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

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
3

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331