4

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.

4
  • 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. Commented Sep 3, 2021 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? Commented Sep 3, 2021 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. stackoverflow.com/a/10460730/4641116 Commented Sep 3, 2021 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. Commented Sep 3, 2021 at 15:01

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.