Inheritance
Inheritance lets a new class take an existing one as a starting point — keep the shared behaviour, layer specialised bits on top.
Basic Inheritance
class Animal {protected: std::string name;public: Animal(const std::string &name) : name(name) {} std::string get_name() const { return name; } void eat() const { std::cout << name << " is eating" << std::endl; }};
class Dog : public Animal {public: Dog(const std::string &name) : Animal(name) {} void bark() const { std::cout << name << " says woof!" << std::endl; }};Dog picks up everything Animal has and tacks on bark(). The public keyword keeps Animal's public members public in Dog.
Constructor Chaining
Derived classes must call the base constructor:
class Shape { std::string color;public: Shape(const std::string &color) : color(color) {} std::string get_color() const { return color; }};
class Circle : public Shape { double radius;public: // Must call Shape's constructor Circle(const std::string &color, double r) : Shape(color), radius(r) {} double area() const { return 3.14159 * radius * radius; }};A Circle object contains a complete Shape at offset 0, followed by Circle's own field. That's why a Circle* can be used as a Shape* with no adjustment: the address is the same. Dog above works the same way, it just adds no fields, so a Dog is exactly the size of its Animal part.
A Circle (x86-64, GCC's libstdc++)
| Offset | Field | Size | Notes |
|---|---|---|---|
| 0x0 (0) | std::string color | 32 | The Shape subobject. std::string is 32 bytes in libstdc++, 24 in libc++. |
| 0x20 (32) | double radius | 8 | Circle's own field. |
sizeof = 40 bytes, 0 of them padding; alignment 8.
Constructors fire base-to-derived (Shape first, then Circle). Destructors run the other way around (Circle first, then Shape). Same RAII ordering you see everywhere else: derived parts get cleaned up before the base they depend on.
Here's that order with three levels instead of two. Write down the six constructor and destructor lines you expect, in order, then run it.
Overloads in the Derived Class Hide the Base Ones
Give Dog a method with the same name as one in Animal, even with different parameters, and you can get a surprise:
class Dog : public Animal {public: Dog(const std::string &name) : Animal(name) {} void eat(int bowls) const { std::cout << name << " eats " << bowls << " bowls" << std::endl; }};
Dog d("Rex");d.eat(2);d.eat();Predict: what do the last two lines print?
Nothing, because the program doesn't compile. d.eat() is an error along the lines of "too few arguments". Name lookup starts in Dog, finds a member called eat there, and stops looking. Animal::eat() is hidden, so overload resolution only ever sees eat(int). Lookup goes by name first and checks the parameters afterwards.
To bring the base version back into play, add using Animal::eat; inside Dog. Then both overloads are visible, d.eat(2) prints Rex eats 2 bowls and d.eat() prints Rex is eating.
When to Use Inheritance
Inheritance models an is-a relationship:
- A
Dogis anAnimal - A
Circleis aShape
If the relationship is has-a, use composition instead:
- A
Carhas anEngine(notclass Car : public Engine)
The Diamond Problem
C++ supports multiple inheritance, which can lead to ambiguity:
class A { public: void method(); };class B : public A {};class C : public A {};class D : public B, public C {};// D has two copies of A's method - ambiguous!Virtual inheritance (class B : virtual public A) fixes this on paper by sharing one A between B and C. In practice, modern C++ steers clear of multiple inheritance and uses interfaces (abstract classes) instead.
Slicing
Watch out when passing derived objects by value:
void process(Animal a) { // a is a copy - if a Dog was passed, the Dog part is sliced off!}
Dog d("Rex");process(d); // Only the Animal part is copiedWorked Example: Slicing, Byte by Byte
Give Dog a member of its own and trace a slice with real values:
class Dog : public Animal { int tricks = 3;public: Dog(const std::string &name) : Animal(name) {}};
Dog d("Rex");Animal a = d;- Layout. A
Dogholds a completeAnimalinside it, the base subobject, followed byDog's own members. With GCC and Clang the base sits at offset 0, so&dandstatic_cast<Animal *>(&d)print the same address. On x86-64 Linux with GCC's standard library,std::stringis 32 bytes, sonamefills offsets 0 to 31,trickssits at 32, and padding roundssizeof(Dog)up to 40. (Clang's libc++ uses a 24-byte string, giving 32. The exact sizes are illustrative; the order is the point.) - The copy.
Animal a = d;callsAnimal's copy constructor, which takes aconst Animal &. ADogconverts to that implicitly, and the reference binds to theAnimalpart ofd. - What arrives. The copy constructor copies what an
Animalhas:name, now"Rex"ina's own buffer. It's never heard oftricks.ais a 32-byteAnimalthat has no idea it came from aDog. - What's lost. Calling anything on
arunsAnimal's code onAnimal's data, for good. Even in the next lesson, once functions arevirtual,astill behaves as anAnimal, because it is one.
Passing by value, as process(Animal a) above does, performs exactly this copy at the call.
Stick to references or pointers when inheritance is in play:
void process(const Animal &a) { // Works correctly with any Animal subclass}One loose end: Animal's destructor isn't virtual. That's fine while every Dog is a local or is destroyed as a Dog, but deleting a Dog through an Animal * is undefined behaviour and in practice skips ~Dog(). The next lesson, on polymorphism, shows why and gives the fix: a virtual destructor in the base class.