I'm trying to understand the consistency in the error that is thrown in this program:
#include <iostream>
class A{
public:
void test();
int x = 10;
};
void A::test(){
std::cout << x << std::endl; //(1)
std::cout << A::x << std::endl; //(2)
int* p = &x;
//int* q = &A::x; //error: cannot convert 'int A::*' to 'int*' in initialization| //(3)
}
int main(){
const int A::* a = &A::x; //(4)
A b;
b.test();
}
The output is 10 10
. I labelled 4 points of the program, but (3) is my biggest concern:
x
is fetched normally from inside a member function.x
of the object is fetched using the scope operator and an lvalue to the objectx
is returned.- Given
A::x
returned anint
lvalue in (2), why then does&A::x
return notint*
but instead returnsint A::*
? The scope operator even takes precedence before the&
operator soA::x
should be run first, returning anint
lvalue, before the address is taken. i.e. this should be the same as&(A::x)
surely? (Adding parentheses does actually work by the way). - A little different here of course, the scope operator referring to a class member but with no object to which is refers.
So why exactly does A::x
not return the address of the object x
but instead returns the address of the member, ignoring precedence of ::
before &
?