I wonder if it’s guaranteed by the C++ standard that single inheritance make the object “grow” upward, that is given a class Base and a class Derived: public Base, and a pointer Derived* ptr, the result of dynamic_cast<Base*>(ptr) will be always numerically smaller or equal to ptr.
I wonder if it’s guaranteed by the C++ standard that single inheritance make the
Share
No. Memory layout is implementation detail.
That being said, I’m not aware of any implementation that doesn’t actually do that, assuming there are no virtual functions. If you introduce a virtual function in
Derived(but there were none inBase), the virtual table pointer could (depending on the implementation) be placed before theBasefields (making theBase*greater thanDerived*).Clarification:
The example above is Visual C++ specific. You can check it out using the following code:
The
base_smaller_or_equalwill befalseunder Visual C++. Judging on @enobayram’s comment, it should betrueunder GCC.In any case, it is an implementation detail and not to be relied upon.