I’m wondering whether or class data members from multiple levels of inheritance are allocated contiguously in C++ compilers. For example if I have the following classes:
class Base
{
public:
int a;
};
class child_1 : public Base
{
public:
int b;
};
class child_2 : public child_1
{
public:
int c;
}
Will the following operation run and output what is expected on all compilers?
child_2 my_obj;
my_obj.a = 3; my_obj.b = 2; my_obj.c = 1;
Base* base_ptr = (Base*)&my_obj;
int* int_ptr = (int*)base_ptr;
cout << "Output 3: " << *int_ptr << endl
<< "Output 2: " << *(int_ptr + 1) << endl;
<< "Output 1: " << *(int_ptr + 2) << endl;
Furthermore, if this is possible, do I need an intermediate cast from the child_2* type to the Base* type as I have above or would the following also be permissable?
int* int_ptr (int*)&my_obj;
Please note that I’m not asking if this is a good idea. Obviously you would want to design your software so that you don’t end up doing stuff like this, but I’m considering such an approach to solve a problem with working with some older code (made by an experienced software engineer, which makes it more complicated).
The compiler that I’m specifically working with is VC++ 2005.
No, the relative layout of derived-class members and base-class members is not specified.
In the current standard, a class is only standard-layout if, among other conditions, it:
In older standards (which would apply to your compiler), there wasn’t even a concept of standard-layout, only POD, and any class with a non-empty base class was not POD.
Your code depends on how a particular compiler lays out the base classes, and is not portable.