Multiple inheritance makes that untrue.
That is not entirely correct. Consider this example:
struct A {};
struct B : A {};
struct C : A {};
struct D : B, C {};
When creating an instance of D
, B
and C
are instantiated each with their respective instance of A
. However, there would be no problem if the instance of D
had the same address of its instance of B
and its respective instance of A
. Although not required, this is exactly what happens when compiling with clang 11
and gcc 10
:
D: 0x7fffe08b4758 // address of instance of D
B: 0x7fffe08b4758 and A: 0x7fffe08b4758 // same address for B and A
C: 0x7fffe08b4760 and A: 0x7fffe08b4760 // other address for C and A
Does virtual inheritance also make that untrue
Let's consider a modified version of the above example:
struct A {};
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};
Using the virtual
function specifier is typically used to avoid ambiguous function calls. Therefore, when using virtual
inheritance, both B
and C
instances must create a common A
instance. When instantiating D
, we get the following addresses:
D: 0x7ffc164eefd0
B: 0x7ffc164eefd0 and A: 0x7ffc164eefd0 // again, address of A and B = address of D
C: 0x7ffc164eefd8 and A: 0x7ffc164eefd0 // A has the same address as before (common instance)
Is the following code correct
There is no reason here to use reinterpret_cast
, even more, it results in undefined behavior. Use static_cast
instead:
A* pA = static_cast<A*>(pB);
Both casts behave differently in this example. The reinterpret_cast
will reinterpret pB
as a pointer to A
, but the pointer pA
may point to a different address, as in the above example (C vs A). The pointer will be upcasted correctly if you use static_cast
.