Learn C++ · lesson 42 of 61 · about 9 minutes
Inheritance
Face the troll king: build a class on top of another with inheritance, reusing and extending its members.
What you'll learn
- Derive a class with : public Base
- Call the base constructor
- Use protected members
The troll king
Past the bank, the troll king guards the stairs. A boss is a monster too: it has a name and health, can be hit and can say how it's doing, so rather than copy all of Monster, the adventure writes class Boss : public Monster. Boss gets every public member of Monster for free and adds just one thing: armour that takes 5 off every blow before it reaches hit(). Monster has no constructor that takes a name and health, so Boss's constructor sets the inherited members in its body.
Is-a relationships
If every Dog is an Animal, Dog can inherit from Animal: class Dog : public Animal { ... };
- Dog gets Animal's public members for free
- Dog's constructor passes values to Animal's constructor in its initialiser list
protectedmembers are hidden from outside code but visible to derived classes
Animal and Dog
#include <iostream>
#include <string>
class Animal {
public:
explicit Animal(std::string name) : name_(std::move(name)) {}
void eat() const { std::cout << name_ << " eats\n"; }
protected:
std::string name_;
};
class Dog : public Animal {
public:
explicit Dog(std::string name) : Animal(std::move(name)) {}
void fetch() const { std::cout << name_ << " fetches the ball\n"; }
};
int main() {
Dog rex("Rex");
rex.eat();
rex.fetch();
}Output
Rex eats
Rex fetches the ballAdding to what's inherited
A derived class can call the members it inherited as if they were its own. That's how a new member function can reuse old behaviour: here heavyHit() doesn't repeat the rules for health, it just calls the inherited hit() with twice the damage.
Reusing hit()
#include <iostream>
#include <string>
class Monster {
public:
std::string name;
int health = 0;
void hit(int damage) {
health -= damage;
if (health < 0) health = 0;
}
};
class Ogre : public Monster {
public:
void heavyHit(int damage) { hit(damage * 2); }
};
int main() {
Ogre o;
o.name = "ogre";
o.health = 30;
o.heavyHit(8);
std::cout << o.name << ": " << o.health << "\n";
}Output
ogre: 14Tip
Inherit only for genuine is-a relationships. If a class just uses another (a Car has an Engine), make it a member instead.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.