I know the memory layout of multiple inheritance is not defined, so I should not rely on it. However, can I rely on it in a special case. That is, a class has only one "real" super class. All others are "empty classes", i.e., classes that neither have fields nor virtual methods (i.e. they only have non-virtual methods). In this case, these additional classes should not add anything to the memory layout of the class. (More concisely, in the C++11 wording, the class has standard-layout)
Can I infer that all the superclasses will have no offset? E.g.:
#include <iostream>
class X{
int a;
int b;
};
class I{};
class J{};
class Y : public I, public X, public J{};
int main(){
Y* y = new Y();
X* x = y;
I* i = y;
J* j = y;
std::cout << sizeof(Y) << std::endl
<< y << std::endl
<< x << std::endl
<< i << std::endl
<< j << std::endl;
}
Here, Y
is the class with X
being the only real base class. The output of the program (when compiled on linux with g++4.6) is as follows:
8
0x233f010
0x233f010
0x233f010
0x233f010
As I concluded, there is no pointer adjustment. But is this implementation specific or can I rely on it. I.e., if I receive an object of type I
(and I know only these classes exist), can I use a reinterpret_cast
to cast it to X
?
My hopes are that that I could rely on it because the spec says that the size of an object must at least be a byte. Therefore, the compiler cannot choose another layout. If it would layout I
and J
behind the members of X
, then their size would be zero (because they have no members). Therefore, the only reasonable choice is to align all super classes without offset.
Am I correct or am I playing with the fire if I use reinterpret_cast from I
to X
here?