I am learning C++ inheritance, so I tried this code by creating a Base class dynamically and made a downcast to its Derived class (obviously its not valid to downcast) in order
Quite simply, at the point that you invoke c->who()
, the static type of c (i.e. the type the compiler knows for c) is child*
and the method who
is non virtual. So the compiler emits the instructions for a call to the address of child::who
.
The compiler does not (and, in general, how could it?) keep track of the true type of the object that would be pointed to by c
at runtime.
If you had any members in child
that are not in parent
, accessing those members in child::who
would have produced an out-of-bounds access, which might cause a SIGSEGV, or other unpleasantness.
Finally, as to whether your observed behavior is guaranteed by the standard, I tend to agree with @P45Imminent: Both parent
and child
satisfy the requirements for POD and child
has no non-static data members. Consequently the runtime layout of parent
and child
objects is required to be indistinguishable per the standard (at least as far as methods of parent
and child
are concerned -- perhaps child
and parent
could have different amounts of padding at the end?). So the line from 9.3.1/2 quoted in one of the comments does not apply IMHO. I'd love to hear from folks more knowledgeable if this assumption on layout is not supported by the standard.