The following code does not compile, and gcc -std=c++11 says it is an invalid static cast:
class A { public: virtual ~A() {} };
class B { public: virtual ~B() {} };
class AD : public A { public: virtual ~AD() {} };
class AB : public B, public A {};
class ADB : public B, public AD {};
int main() {
ADB adb;
ADB* ptr = &adb;
AB* cast = static_cast<AB*>(ptr);
return 0;
}
I would like to cast a class of type ADB to AB. This feels like it should be safe to do - after all, the memory structure of ADB is B followed by AD, which itself is just A followed by AD's own members. Thus it would seem that literally forcing compiler to interpret the pointer ptr as an AB would always be defined:
class A { public: virtual ~A() {} };
class B { public: virtual ~B() {} };
class AD : public A { public: virtual ~AD() {} };
class AB : public B, public A {};
class ADB : public B, public AD {};
int main() {
ADB adb;
ADB* ptr = &adb;
AB* cast = reinterpret_cast<AB*>(ptr);
return 0;
}
This does not compile either, resulting in the linker complaining about undefined references
to the vtable and to operator delete(void*).
So clearly at some point the vtable pointers are not "syncing up" when casted, in which case I somehow need to cast the individual base class of AD of ADB to just the A of AB. I'm not exactly sure about that, just guessing. How can I do this or something equivalent to it?
T. In order to avoid overhead, I'd be nice to store astruct { meta m; T t; }, the pointer for which which would be containedmytype<T>. But in order to allow casting frommytype<T>tomytype<TBase>, I am instead storing a pointer to astruct stored : public meta, public T, in hopes of accomplishing what's in my question.ADBtoAB, but I wanted to convey the structure of the types in memory.