About dynamic cast and address of base and derived objects

前端 未结 4 1940
名媛妹妹
名媛妹妹 2021-01-22 11:10

I was reading through some of effective c++ and I realized I may be incorrect in my thinking along the way.

class A
{
    public:
    void laka()
    {
        c         


        
4条回答
  •  一个人的身影
    2021-01-22 11:22

    1. When I just output the address of the plain old &b above, is the address displayed the starting address of the derived object or the base object within b?

    You could say "yes", it's the starting address of the base object class A within b (which is the same as the starting address of the derived object b itself) ... but the derived object is not really a "separate" object from the base-object. The derived object is also not something that will necessarily start with a fixed offset from the base object, especially if it's a non-POD class (plain-old-data-type) with virtual functions since the first address of both the base and derived objects is a pointer to a v-table specific to either the base or derived object. So you can't really "slice" apart a derived object into a "base-object" and derived object, other than the fact that for most compiler instances, the derived objects non-static data members will come after an offset from the non-static data memebers of the base-object. But again, arbitrary "slicing" will cause issues with the v-table pointer, and also for non-POD classes, any private non-static member objects may be allocated in an "optimized" fashion that may make the memory layout between the base and derived objects something that is not exactly a clean "slice".

提交回复
热议问题