3

Let's say I have the following variable:

MyObject* obj = ...;

If this object has the field foo, there are two ways of accessing it:

  1. obj->foo
  2. (*obj).foo

Are there any differences between using one method over the other. Or is the first method just syntactic sugar for the second?

I was thinking maybe the first one could cause the copy constructor of the object to be called since it is now holding onto the value.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • Yes, I'm pretty sure it's just syntactic sugar. At least in your case it is; the behavior might be different when overloaded operators are involved. – mediocrevegetable1 Sep 03 '21 at 13:16
  • "I was thinking maybe the first one could cause the copy constructor of the object to be called since it is now holding onto the value." Why do you think so? – Alessandro Teruzzi Sep 03 '21 at 13:31
  • For overloaded `operator->`, the `->` has the "drill down" property where it is applied recursively until the resulting object is a pointer. q.v. https://stackoverflow.com/a/10460730/4641116 – Eljay Sep 03 '21 at 13:34
  • @AlessandroTeruzzi Pass by value causes copy constructor to be called, so I was thinking that perhaps dereferencing is passing the object by value to the piece of code that is dereferencing it. Just a thought, I figured that wasn't the case. – David Callanan Sep 03 '21 at 15:01

3 Answers3

10

There is no difference when obj is a pointer.

If obj is an object of some class, obj->foo will call operator->() and (*obj).foo will call operator*(). You could in theory overload these to do totally different behavior, but that would be a very badly designed class.

Kevin
  • 6,993
  • 1
  • 15
  • 24
6

According to §7.6.1.5 ¶2 of the ISO C++20 standard, the expression obj->foo is converted to (*obj).foo. So it is just syntactic sugar. Both are equivalent.

I was thinking maybe the first one could cause the copy constructor of the object to be called since it is now holding onto the value.

No constructor will be called, because no new object is created.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
3

is the first method just syntactic sugar for the second?

Yes.

I was thinking maybe the first one could cause the copy constructor of the object to be called

No.


Technically, there is a difference that operator. cannot be overloaded for classes while operator-> can be overloaded. Operators -> and * should be overloaded such that it->foo and (*it).foo remain equivalent, although the language technically doesn't enforce that.

eerorika
  • 232,697
  • 12
  • 197
  • 326