How do data members get aligned / ordered if inheritance / multiple inheritance is used? Is this compiler specific?
Is there a way to specify in a derived class how
As soon as your class is not POD (Plain old data) all bets are off. There are probably compiler-specific directives you can use to pack / align data.
Compilers generally align data members in structs to allow for easy access. This means that data elements will normally start on word boundaries and it gaps will normally be left in a struct to ensure that word boundaries are not straddled.
so
struct foo { char a; int b; char c; }
Will normally take up more than 6 bytes for a 32 bit machine
The base class is normally layed out first and the derived class it layed out after the base class. This allows the address of the base class to equal the address of the derived class.
In multiple inheritance there is an offset between the address of a class and the address of the second base class. >static_cast
and dynamic_cast
will calculate the offset. reinterpret_cast
does not. C style casts do a static cast if possible otherwise a reinterpret cast.
As others have mentioned, all this is compiler specific but the above should give you a rough guide of what normally happens.
I can answer one of the questions.
How do data members get aligned / ordered if inheritance / multiple inheritance is used?
I've created a tool to visualize the memory layout of classes, stack frames of functions and other ABI information (Linux, GCC). You can look at the result for mysqlpp::Connection class (inherits OptionalExceptions) from MySQL++ library here.