Re: Memory layout of class
Heskov Dmitry schrieb:
What is the memory layout of an object, and the derived object.
Does it depend on the compiler ?
In general yes.
The standard only makes few restrictions to the memory layout. E.g.
members of one class that are not intercepted by private: or so have to
be in the order that they are defined.
But there are no restrictions about base classes. They need not to have
a hard relation to the derived class at all. In case of virtual base
classes (e.g. interfaces) this ist obviously the case.
ptr = (int *)&b;
From here it is definitely undefined behaviour. B is no POD.
B need not to start with A and furthermore the first storage ob B might
not be any member at all.
*ptr = 1000;
*ptr = 2000;
*ptr = 3000;
*ptr = 4000;
is setting only the private element of class A to 1000, rest are not
Undefined behaviour, as I said.
However, many compilers start with the members in the order as they are
declared and place bas classes before their derived class. Furthermore
everything is usually preceeded with a virtual table pointer if the
class is polymorphic. Each polymorphic base class has it's own virtual
table pointer, except for the first base class. In this case the virtual
table of the base is a slice of the virtual table of the derived
class(es), therefore their two vtbl pointers are collapsed.
This is as many compilers behave. But not one of this words is reliable.
It may even change with the compiler version. E.g. the compiler may sort
members by size and/or alignment to save padding space. Debug memory
management may place additional guard areas at certain locations in the
So the answer is quite simple. You must not ask this question, since the
answer will not be reliable. Do not rely on the memory layout of the
class tree. Only PODs have a more or less defined memory layout.