C++ Inheritance: Derived class pointer to a Base class invokes Derived class method

前端 未结 6 1786
眼角桃花
眼角桃花 2021-01-25 20:28

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

6条回答
  •  孤街浪徒
    2021-01-25 20:45

    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.

提交回复
热议问题