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

StackOverflow https://stackoverflow.com/questions/21457675

  •  05-10-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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

Outras dicas

You create an object of type A. So the memory will be allocated for this type of object. It will large enough to contain int _a and vptr. I think if the size of pointer is equal to 4 then 8 bytes will be allocated for an object of type A.

You should understand that base classes know nothing about what derived classes will be defined based on the base classes.

However if you would write

A* a = new B();

then an object of type B would be created in memory. But the static type of pointer a is A *. So you could not access data member _b without dynamic_cast or static_cast pointer a to type B *.

Class A doesn’t know about its derived classes (they might be physically completely separate, in other compilation units, loaded later at run time). Even if it did, there’s no sense in allocating space for all its derived classes – because it is not its derived classes.

Just like parents don’t go to school for their children, a class does not act in its derived classes’ stead.

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?

These members do not go into the vtable anyway. As for members which do go into the vtable (= virtual functions), the above applies: a base class’ vtable is only big enough for the virtual functions it declares, and no others.

Only A.

Otherwise A would grow when someone creates new classes: C, D, E, ... all of them deriving from A. This would be absurd.

It doesn't create a vtable - there's (typically) just one of those per class. It creates an object, of type A with enough space for the member(s) of A. It doesn't create an object of type B (or anything else) since that's not the type specified by the new expression.

NO and the reason is really simple:

A class does not contain any of B class members or methods.

=> So, memory space for B is not necessary

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top