Calling virtual member functions of a class using a pointer to the base class is of course a very common thing to do in C++. So I find it strange that it seems impossible to do the same thing when you have a member pointer instead of a normal pointer. Please consider the following code:
struct B
{
virtual void f();
};
struct D : B
{
virtual void f();
};
struct E
{
B b;
D d;
};
int main()
{
E e;
// First with normal pointers:
B* pb1 = &e.b; // OK
B* pb2 = &e.d; // OK, B is a base of D
pb1->f(); // OK, calls B::f()
pb2->f(); // OK, calls D::f()
// Now with member pointers:
B E::* pmb1 = &E::b; // OK
B E::* pmb2 = &E::d; // Error: invalid conversion from ‘D E::*’ to ‘B E::*’
(e.*pmb1).f(); // OK, calls B::f()
(e.*pmb2).f(); // Why not call D::f() ???
return 0;
}
Visual C++ goes on to say:
error C2440: 'initializing' : cannot convert from 'D E::* ' to 'B E::* '
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
I don't understand why these are 'unrelated'. Why is this not possible?
Edit:
I am trying to keep this a C++ question and not about the particular problem I am trying to solve, but this is essentially what I want to do:
std::vector<B E::*> v;
v.push_back( &E::b ); // OK
v.push_back( &E::d ); // Error
B& g( E& e, int i )
{
return e.*v[i];
}
E is a class containing several members derived from B. The vector v is used to organize (eg reorder) member pointers to these members. Vector v changes infrequently. The function g() allows you to select one of the members of E using an index into v. It is called very often and each time with a different E.
If you think about it, v is just a lookup table of offsets. The function g() simply selects one of these offsets and add it to the E* in order to return the B*. The function g() is inlined by the compiler and compiles to just 4 CPU instructions, which is exactly what I want:
// g( e, 1 )
mov rax,qword ptr [v (013F7F5798h)]
movsxd rcx,dword ptr [rax+4]
lea rax,[e]
add rcx,rax
I cannot think of any reason why the standard would not allow a D E::* to be converted to a B E::*.