Inheritance and Polymorphism
Build class families, reuse code, and let one call do many things
- build a base class and a derived class with
: public Base, - reuse and extend inherited members, and use
protected, - call base constructors from a derived constructor,
- use
virtualfunctions andoverridefor polymorphism, - explain why a base class needs a
virtualdestructor.
1. What is inheritance?
Inheritance lets one class (the derived class) automatically get the members of another class (the base class). The derived class can then add extra things of its own. We write it with a colon and public:
#include <iostream>
using namespace std;
class Animal { // base class
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
class Dog : public Animal { // derived class
public:
void bark() {
cout << "Woof!" << endl;
}
};
int main() {
Dog d;
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
return 0;
}
Output:
This animal eats food.
Woof!
Dog never wrote an eat() function, yet d.eat() works because Dog inherited it from Animal. We say "a Dog is-an Animal". This is the "is-a" relationship.
2. Picture a class family
One base class can have many derived classes. The arrow means "inherits from" and always points from a child up to its parent:
Both Dog and Cat get everything public in Animal, so shared code lives in one place. Fix a bug in Animal once, and every derived class is fixed too.