C++ Inheritance
Inheritance builds a new class on top of an existing one. The new derived class gets all the members of the base class and can add its own. It models an "is a" relationship: a dog is an animal, a savings account is an account.
A base and a derived class
#include <iostream>
#include <string>
class Animal {
protected: // visible in derived classes
std::string name;
public:
explicit Animal(const std::string& n) : name(n) {}
void eat() const { std::cout << name << " is eating\n"; }
};
class Dog : public Animal {
public:
explicit Dog(const std::string& n) : Animal(n) {} // call the base constructor
void bark() const { std::cout << name << " says Woof\n"; }
};
int main() {
Dog d("Bruno");
d.eat(); // inherited from Animal
d.bark(); // Dog's own
return 0;
}Bruno is eating Bruno says Woof
class Dog : public AnimalmakesDogderive fromAnimal. Withpublicinheritance, the public members ofAnimalstay public inDog.- The base constructor is called in the derived constructor's initializer list:
Animal(n). protectedmembers are hidden from the outside but usable by derived classes;privatemembers of the base are not reachable inDogat all.
Adding and changing behaviour
A derived class can add members and also define a method with the same name as the base's, which hides the base version for Dog objects. To make such a replacement work through a pointer or reference to the base class, the base method must be virtual, which is the topic of Polymorphism.
Multilevel inheritance
A derived class can itself be a base:
#include <iostream>
class Account {
protected:
double balance = 0;
public:
void deposit(double a) { if (a > 0) balance += a; }
double getBalance() const { return balance; }
};
class SavingsAccount : public Account {
double rate;
public:
explicit SavingsAccount(double r) : rate(r) {}
void addInterest() { balance += balance * rate; }
};
class StudentSavings : public SavingsAccount {
public:
StudentSavings() : SavingsAccount(0.05) {}
void deposit(double a) { SavingsAccount::deposit(a + 10); } // a small bonus on every deposit
};
int main() {
StudentSavings s;
s.deposit(1000);
s.addInterest();
std::cout << s.getBalance() << "\n";
return 0;
}1060.5
SavingsAccount::deposit(...) calls the base version explicitly.
Inheritance or a member?
Use inheritance only for a real "is a" relationship. When a class only uses another (a car has an engine), make it a member instead; this is called composition, and it is usually the simpler and more flexible choice.
Practice exercises
- Add a
Catclass with ameowmethod and use both inherited and own methods. - Give
Animalanagemember and a constructor that sets it; pass it fromDog's constructor. - Design classes for
Vehicle,CarandBikewith shared and own members.