Suppose I have:
class Base {
public:
virtual void Nothing() {}
};
class MiddleDerived : public Base {
virtual void Nothing() {}
};
class Derived : public MiddleDerived {
virtual void Nothing() {}
};
and my code goes like this:
Derived* object = new Derived();
Base* base = object; //implicit conversion here
void* derivedVoid = object;
void* baseVoid = base;
Should I expect that baseVoid == derivedVoid
?
I know that most implementations work this way but is it guaranteed?
What you "should expect" can be different from what's guaranteed.
A static_cast
up or down an inheritance chain can change the address.
The canonical example where this occurs in practice is where a base class is non-polymorphic and a derived class introduces some virtual function, which with many compilers then introduce a vtable pointer at the start of each derived object.
I think the part of the standard that deals with this is §5.2.9 (13)
Which states (in a nutshell) that a T* cast to a void* and then back to a T* shall refer to the same object.
However there is no stipulation The address of Derived
must be the same as the address of its Base
.
So my answer would be, "no - code that expects this equivalency is ill-formed inviting undefined behaviour".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With