1

As I just learned, for a pointer p there are two equivalent ways of accessing a member of the referenced object, namely p->foo and (*p).foo.

Are there technical arguments which is best to use?

Note: One argument I read about, is that . is safer because it cannot be overloaded, while -> can. I guess, however, there must be more arguments, as in most C++ code I work on I only see the ->-construct.

Community
  • 1
  • 1
flonk
  • 3,726
  • 3
  • 24
  • 37

2 Answers2

5

For raw pointers, operators cannot be overloaded.

For smart pointers, the operator * can be overloaded as well and should return the same object as operator -> (although dereferenced).

The operator -> is IMO much better readable than wrapping everything in parentheses, especially when you would use it multiple times in a row.

There is a slight difference that operator -> is chained (operator -> is called on the returned object and it can again be overloaded) while operator * is not but it is unusual to have a situation where this would end in different results.

StenSoft
  • 9,369
  • 25
  • 30
0

Generally, both approaches do the same thing:

p->member
(*p).member

except for situations where you overload operators to get a specialized behavior.

As far as which is 'better' it depends on what better means... p->member is a lot cleaner and makes the code easier to understand, which is always a big plus.

Take a more complicated example:

struct NewType
{
   int data;
}

void foo (NewType **p)
{
   int temp0 = (*p)->data;
   int temp1 = (*(*p)).data;
}

both temp0 and temp1 will have the same value, but it's a lot easier to see what's going on for temp0.

Pandrei
  • 4,843
  • 3
  • 27
  • 44