Pergunta

I have a class 'base' with a virtual destructor and thus a VTable and corresponding VTPR in it, and a class derived from it:

class base {
public:
    virtual ~base() {}
};

class der : base {};

main()
{

    int a = sizeof(base); // = 4 , fine !

    int b = sizeof(der);  // = 4 too ?
}

Now as derived class too is virtual, it'll have a VPTR of its own, but since it also has a subobject of the base class with a VPTR in it, shouldn't the size of the class 'der' be 8 bytes i.e. the size of the VPTR of the class 'der' + size of VPTR of the subobject of class 'base'? (when sizeof(void*) = 4 bytes ).

So basically my question is : When the subobject of class 'base' is made in 'der' does it have a seperate new VPTR ? And if it is so then why its size is not getting added while calculating the size of 'der'?

Can somebody please clarify this.

Foi útil?

Solução

This is all implementation-specific. But in practice, there will only be one vptr in the derived class; there is no need for two. The whole point of the vptr is it's what gets used to dynamically call the correct override of the virtual function; der objects will simply have a different pointer value to base objects.

[Note: Your example is probably confused by the fact that you are (unintentionally?) using private inheritance, rather than the more typical public inheritance...]

Outras dicas

I think you're confusing vtables and vptrs. Each class will have a vtable, and each object will store a pointer to its vtable as the vptr. The vtable is like a static global, it is shared between all instances of the class and thus doesn't take any space in the object.

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