I got told that if i do inheritance when the base class contains protected member variables and a child class will construct the base class, it will duplicate it's members in memory. Example:
class Animal
{
public:
virtual std::string& sound() { return m_sound; }
virtual void setSound(std::string& sound) { m_sound = sound; }
virtual int age() { return m_age; }
virtual void setAge(int age) { m_age = age; }
protected:
Animal(std::string sound, int age) : m_sound(sound), m_age(age) { }
int m_age;
std::string m_sound;
};
class Dog : public Animal
{
public:
Dog(int speed) : Animal("Waff!!", 3), m_speed(speed) {}
virtual int speed() { return m_speed; }
virtual void setSpeed(int speed) { m_speed = speed; }
protected:
int m_speed;
};
So using the example above, what I meant in other words, that if I create a Dog
object, it'll allocate 2 times memory for m_sound and m_age.
That completely didn't make any sense to me and I've been wondering why would the compiler would do such a thing unless the information I heard is misleading.
So say in main we create:
Dog bulldog(5);
Debugging this code and looking at the memory here is what I got:
I would like to know what exactly gets allocated in the region of memory where the questions marks between the parent class data and the child.