How would you explain this difference in pointer to members of base and derived class using standard quotes?

Viewed 314

demo:

#include<iostream>
struct A { int i = 10; };
struct B : A { };

int main(){
    std::cout << "decltype(&B::i) == int A::* ? " << std::boolalpha
              << std::is_same<decltype(&B::i), int A::*>::value << '\n';    //#1
    A a;
    std::cout << a.*(&A::i) << '\n';

    std::cout << "decltype(&B::i) == int B::* ? "
              << std::is_same<decltype(&B::i), int B::*>::value << '\n';    //#2
    B b;
    std::cout << b.*(&B::i) << '\n';
}

The code prints

decltype(&B::i) == int A::* ? true
10
decltype(&B::i) == int B::* ? false
10

I used the example in [expr.unary.op]/3, where the standard says that the type of &B::i is int A::*, but that is not normative.

1 Answers

From the paragraph you link to, emphasis mine:

If the operand is a qualified-id naming a non-static or variant member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m.

"Some class C" means it need not be the same class as the one mentioned by the qualified-id. In this case, i is a member of A, and remains a member of A even when named by &B::i. The type of &B::i is therefore int A::*, which you can verify by the test

std::is_same<decltype(&B::i), int A::*>::value

According to [class.qual]/1, member lookup follows the algorithm detailed in [class.member.lookup]. It is according to the rules there, which inspect the sub-object from which the member i comes from, that the class C is determined. Since i is a member of the sub-object A, the class of the pointer to member is determined to be A.

Related