0

Let us suppose to have the following code:

struct Foo {
  int _data;
};

struct Bar : public Foo {
  int* bar() {
    return &Foo::_data;  // <--- Compiler ERROR!
  }
};

The expression &Foo::_data is evaluated as int Foo::* (i.e., int-pointer to a member of the class Foo). Therefore, the return statement generates a compiler error because there is no implicit cast conversion.

Godbolt Snippet Here.

Of course, it is easy to fix this: return &(Foo::_data);. Indeed, my intent is to return a pointer to the variable _data.

In accordance with the C++ precedence operator table, the operator:: should have higher precedence than operator&.

My question is: why without parenthesization it seems operator& to have higher precedence?


Note: The compiler error seems to be consistent across different compilers and versions. So I am probably missing something :)

Note: I am not interested in how to fix the problem (I have already proposed a solution in the question, or just using _data). I more interested to understand why my assumption is not true.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
BiagioF
  • 9,368
  • 2
  • 26
  • 50

0 Answers0