Should I expect upcasts and downcasts in single inheritance not to adjust the pointer?

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 is as follows:

 Derived* object = new Derived(); Base* base = object; //implicit conversion here void* derivedVoid = object; void* baseVoid = base; 

Should I expect baseVoid == derivedVoid ?

I know that most implementations work this way, but is this guaranteed?

+5
source share
2 answers

What you “should expect” may differ from what is guaranteed.

A static_cast up or down inheritance chain can change the address.

The canonical example where this happens in practice is that the base class is not polymorphic, and the derived class represents some virtual function that, with many compilers, then introduces the vtable pointer at the beginning of each derived object.

+2
source

I think that the part of the standard that deals with this is §5.2.9 (13)

Which states (in a nutshell) that T * passed to void *, and then back to T *, refer to the same object.

However, there are no conditions. The Derived address must be the same as its Base address.

So my answer would be: "no-code that expects this equivalence to be a poorly formed undefined prompt."

+2
source

Source: https://habr.com/ru/post/1241416/


All Articles