2

Possible Duplicate:
C++ - Difference between (*). and ->?

What is the difference between this:

(*ptr).f();

and this:

ptr->f();

in where the ptr is a pointer to C++ class which has a function f?

Community
  • 1
  • 1
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
  • 1
    The only difference is that the compiler will transform `ptr->f()` into `(*ptr).f()` (aka, it's just a shortcut). – Xeo Feb 01 '13 at 13:48

3 Answers3

8

There's no difference at all. (*ptr).f(); is the uglier way to do this.

Actually, if ptr is some smart pointer and its operator* and operator-> are overloaded and execute some side-effects, then you may have a problem with this. But this is really, really bad thing to do. It's as evil as #define true false

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • +1 for mentioning that you should (almost) never define operators in a way that violates the principle of least surprise. – us2012 Feb 01 '13 at 14:33
8

If ptr is a normal pointer, then both are equivalent. ptr->f is a short-cut to dereference the pointer (equivalent to (*ptr)) and access the member of the dereferenced object (equivalent to .f).

If ptr is a class that overloads operator-> and operator*, then they will each call different operator overloads, and so could have different behaviour.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Aside from stylistic/typing differences, there is no difference. It's exactly the same as (*ptr).member = 7; vs ptr->member = 7; when using a pointer to a structure or class.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227