A char will be inserted into a class object if it is empty - 1 byte for an empty class object
class X {};
class Y: public virtual X {};
class Z: public virtual X {};
class A: public Y, public Z {}
The size of Y and Z are decided by:
- overhead of the language - a pointer is created in derived class object and points to virtual base class subobject
- optimization done by compiler - some new compiler will not insert the 1 byte for virtual base class subobject
- memory alignment
X: 1 byte + Y: pointer which points to virtual base class subobject 4 bytes + memory alignment 3 bytes = 8 bytes
static data members are stored in data segment of the program.
Read/Write of Data Member
static data member is not stored in class object, so following situations have the same behaviour and performance.
// chunkSize is static data member
origin.chunkSize = 250;
pt->chunkSize = 250; // will be converted to origin.chunkSize = 250 inside by compiler
this pointer (implicit class object) is used by member function to access nonstatic data member of class object.
to access nonstatic data member - compiler takes start address of class object and add an offset onto it.
origin._y = 0.0;
// will be converted to
&origin + (&Point3d::_y-1); // the offset value of points which point to data member is always +1
If the class is a derived class object and there is at least one virtual base class, and the data member is from virtual base class. Then an additional link is needed to get the exact offset value of data member (compiler does not know the exact offset value when compiling).
origin.x = 0.0;
pt->x = 0.0;
Concrete inheritance will not induce additional space or time consuming, just like C struct.
notice padding - padding exists in every single class object.
For those virtual functions, additional cost is from:
- a virtual function table
- a vptr which points to virtual function table
- expanding constructor - initialize vptr in all derived class object or base class object
- expanding destructor
For virtual inheritance:
if a class object has more than one virtual base class subobjects, it will be divided into shared zone and consistent zone
additional cost:
- pointers will be saved in derived class object and point to each virtual base class subobject
- or Microsoft compiler will create a virtual base class table
- or offset value of virtual base class is stored in virtual function table
Virtual inheritance will impact the optimization ability of compiler by those indirect linking.