I am working on designing a small system and am wondering about a nuance of how memory is allocated for derived classes.
If I have two classes
class foo {
public: int a;
Foo(): a(0) {};
};
class bar : public foo {
public: int b;
Bar() : Foo() , b(0) {}
};
and then do something like this in another method
Bar* purple = new Bar();
I know that both constructors will be called (for Foo and Bar) but how will the memory be allocated. Is the memory for both ‘a’ and ‘b’ allocated at the same time, as they are both a part of Bar class, or is the memory allocated for ‘a’ when the Foo constructor is called and the memory for ‘b’ allocated when the Bar constructor is called.
Thanks in advance for the help.
new Baris just one contiguous allocation, as isnew Bar[n].It may help to think of like this:
is similar to:
Behind the scenes, the constructor is also called, and in some cases the allocation may be greater than
sizeof(Bar);new[]is a common case where it is greater because the array’s count is secretly stored in the allocation in many implementations.Update
The sizeof
Baritself is the size required to store the type; its members, its bases, a pointer to its vtable, etc. – all with native alignment (by default). The compiler may also introduce padding.Therefore, the single contiguous allocation will be sufficiently large enough to hold everything both foo and bar require, including
foo::aandbar::b.In more detail: where are member-vars of a class on the heap stored?