Member coercion pointer to the most derived type

Consider a hierarchy of this type:

struct A {
    int x;
};

struct B : A {
    int y;
};

      

The type &B::y

is equal int B::*

, but the type &B::x

is equal int A::*

. It can be converted to int B::*

what I need, but I need to explicitly do that conversion.

Is there a convenient way to infer a type as a pointer to a member of a specified class? After all, if I wanted A::*

to x

, I could do &A::x

.

+3


source to share


1 answer


Such a conversion would be impossible in the case of virtual inheritance. Let be

struct A {
  int x;
};

struct B : virtual A {
  int y;
};

      

and two functions,

int f(B* pB) {
  int A::*pX = &A::x; // or &B::x, identical but clearer this way
  return pB->*pX;
}

int g(B* pB) {
  int B::*pY = &B::y;
  return pB->*pY;
}

      



f(B*)

it is necessary to search the vtable to find the underlying instance pointer A

inside *pB

, whereas g(B*)

only applies the offset to pB

. Therefore an object &A::x

cannot be expressed as an instance of a type int B::*

, it needs different runtime logic to evaluate with a pointer to B

than int B::*

.

Even if it B

is the most derived class here and now, it is possible to define another class C

that inherits as A

well as B

in a different compilation unit and wants to pass C*

to f()

. Therefore, an offset A

inside is B

not possible for a fixed one.

One could argue that the language can allow the transformation if there is no virtual inheritance, or in anonymous namespaces, or ... but it was probably easier to disallow it consistently.

0


source







All Articles