class ClassABC
{
public:
ClassABC(){}
virtualvoid Display(){ cout<<"\nClassABC::Display()\n"; }
private:
int _a;
};
class ClassXYZ:public ClassABC
{
public:
ClassXYZ(){}
virtualvoid Display(){ cout<<"\nClassXYZ::Display()\n"; }
private:
int _b;
};
int main()
{
cout<<"\n Test virtual ptr inherits to derived class \n";
ClassABC obj1;
cout<<"\n Size of ClassABC::obj1 : "<<sizeof(obj1);
ClassXYZ obj2;
cout<<"\n Size of ClassXYZ::obj2 : "<<sizeof(obj2);
}
Output=========================
Size of ClassABC::obj1 : 8
Size of ClassXYZ::obj2 : 12
===============================
But ClassXYZ also have virtual function "Display2()" so it should have its own Virtual pointer,So size of obj2 should be:
from base class : 8
_b : 4
ClassXYZ::vptr : 4
So total is 16 bytes.
There is one inherited from Base, so vtable pointer is still needed. If your class has virtual functions (declared in it or inherited from parent) add vtable cost.
Another thing which can change expected class size is padding: unused bytes added to ensure aligment.
For example I would expect following structure to have size of 16 bytes
Now, one Vptr is inherited from Base class and another required for own class.
No. It is not inherited, as it does not exist as far as language rules concerned. You cannot inherit something which does not exist. Virtual table is implementation detail, added by compiler to make virtual magic work. You either have vtable or not.
That means Vptr of base class not inherits to its Derived class?
Ok then its correct :
ClassABC : object size - 8 bytes (4 for int member and +4 for Vptr)
ClassXYZ : object size - 12 bytes(4 from Base class +4 for int member and +4 for OwnVptr)
Even though the derived class doesn't inherit the vtable pointer, the derived class still inherits virtual member functions and so it gets a vtable pointer anyway.
First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table.
Yes. Virtualness is poisonous: once you have virtual table, you and your children will always have it.
Second, every instance of class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual pointer.
There is one virtual table per class, and every instance of class holds a pointer to it. This is done to not clutter classes: if there is 15 virtual functions, there would be 15 entries in class virtual table, but each instance holds only a single pointer to it and not whole table.