C++ is there a difference between dereferencing and using dot operator, vs using the arrow operator

Viewed 320

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.

3 Answers

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.

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.

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.

Related