Search code examples
c++memory-managementvtable

when allocating memory to an object of base class, does the memory for the derived class is allocated too?


class A {
     private:
           int _a;
     public:
           //some virtual methods...
};

class B : public A {
     private:
           int _b;
     public:
            //methods..
};

when declaring a pointer of type A like:

A* a = new A();

does the vtable created fits the size of both ints a and b or does the space allocated fits only an object of type A?


Solution

  • Of course not!!

    The class A does not know of the existence of class B

    But class B inherits A so it does indeed know A

    In other words, what it happens is the opposite:

    The memory space allocated when creating an instance of class B is enough to hold the members of class B and the inherited members of class A