WeCodeAcademy

C++ Inheritance and Polymorphism

A class can inherit from another. A virtual function lets the right version run through a base-class pointer.

ExampleC++
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Animal {
 public:
  virtual string speak() const { return "..."; }
  virtual ~Animal() = default;
};

class Dog : public Animal {
 public:
  string speak() const override { return "woof"; }
};

class Cat : public Animal {
 public:
  string speak() const override { return "meow"; }
};

int main() {
  vector<unique_ptr<Animal>> pets;
  pets.push_back(make_unique<Dog>());
  pets.push_back(make_unique<Cat>());
  pets.push_back(make_unique<Animal>());
  for (const auto &p : pets) cout << p->speak() << endl;
  return 0;
}
Output
woof
meow
...
Quick check

Which keyword enables polymorphism on a base-class function?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.