C++ allocating space for objects using inheritance

Viewed 1699

I've got a question about how a C++ compiler knows how much space it needs to allocate for an object when using inheritance.

Imagine the following classes, for an adult and a child which extend a Person class, but where a child has a short book with them.

class Person
{

};

class Adult : public Person
{
    //No book
};

class Child : public Person
{
   char book[1000]; //Stores the book
};

Now if you create an array of Person objects, and add objects to them:

Adult adult1;
Child child1;

Person people[2];
people[0] = child1;
people[1] = adult1;

My question is: How does the compiler know how much space it needs to ensure the array is a contiguous memory block, if it doesn't know whether the array will be filled with Adult or Child (which are much different sizes) objects?

I hope this makes enough sense to answer...

Thanks

6 Answers
Related