Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ allocating space for objects using inheritance

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

like image 729
Freddie Avatar asked Jul 30 '11 17:07

Freddie


Video Answer


2 Answers

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

The people array cannot contain Adult or Child objects: it can only contain Person objects.

When you perform the assignment people[0] = child1;, what actually happens is the Person parts of the child1 object are assigned to people[0]. All of the Child parts are effectively ignored.

This behavior, where only the base class parts of an object are copied, is called "slicing."

To get polymorphic behavior in C++, you must use either pointers are references. Since it is impossible to have an array of references, you would need to use an array of pointers.

like image 114
James McNellis Avatar answered Sep 30 '22 15:09

James McNellis


Since your array is of type Person, the compiler doesn't know to declare enough space for children and adults. It just declares enough for two people.

Each time you put in a child or adult, the object will get "sliced" off, keeping only the Person part of the object.

The standard way to get around this is to declare an array of People pointers (which are all of constant size regardless of what they point to, since they're really just memory addresses), which can point to objects of any of your classes.

like image 38
Cameron Avatar answered Sep 30 '22 16:09

Cameron