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:
xis fetched normally from inside a member function.xof the object is fetched using the scope operator and an lvalue to the objectxis returned.- Given
A::xreturned anintlvalue in (2), why then does&A::xreturn notint*but instead returnsint A::*? The scope operator even takes precedence before the&operator soA::xshould be run first, returning anintlvalue, 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 &?