Skip to main content
Be Bitwise
C++Classes & OOP

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

cpp
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:

cpp
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++)

0x00x28
OffsetFieldSizeNotes
0x0 (0)std::string color32The Shape subobject. std::string is 32 bytes in libstdc++, 24 in libc++.
0x20 (32)double radius8Circle's own field.

sizeof = 40 bytes, 0 of them padding; alignment 8.

Key Concept

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.

Try itAdd a fourth class, Puppy : Dog, and check the order still mirrors itself.
C++ (GCC 9.2.0)

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:

cpp
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 Dog is an Animal
  • A Circle is a Shape

If the relationship is has-a, use composition instead:

  • A Car has an Engine (not class Car : public Engine)

The Diamond Problem

C++ supports multiple inheritance, which can lead to ambiguity:

cpp
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:

cpp
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 copied

Worked Example: Slicing, Byte by Byte

Give Dog a member of its own and trace a slice with real values:

cpp
class Dog : public Animal {
int tricks = 3;
public:
Dog(const std::string &name) : Animal(name) {}
};
Dog d("Rex");
Animal a = d;
  1. Layout. A Dog holds a complete Animal inside it, the base subobject, followed by Dog's own members. With GCC and Clang the base sits at offset 0, so &d and static_cast<Animal *>(&d) print the same address. On x86-64 Linux with GCC's standard library, std::string is 32 bytes, so name fills offsets 0 to 31, tricks sits at 32, and padding rounds sizeof(Dog) up to 40. (Clang's libc++ uses a 24-byte string, giving 32. The exact sizes are illustrative; the order is the point.)
  2. The copy. Animal a = d; calls Animal's copy constructor, which takes a const Animal &. A Dog converts to that implicitly, and the reference binds to the Animal part of d.
  3. What arrives. The copy constructor copies what an Animal has: name, now "Rex" in a's own buffer. It's never heard of tricks. a is a 32-byte Animal that has no idea it came from a Dog.
  4. What's lost. Calling anything on a runs Animal's code on Animal's data, for good. Even in the next lesson, once functions are virtual, a still behaves as an Animal, 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:

cpp
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.