C++ inheritance and virtual functions

A derived class inherits the members of its base class. Without virtual, a call through a base reference or pointer uses the base class's version. Marking the base function virtual makes the call dispatch at run time to the version of the actual object. override on the derived function asks the compiler to check that it really overrides a virtual function.

C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Animal {
 public:
  explicit Animal(std::string name) : name_(std::move(name)) {}
  virtual ~Animal() = default;
  virtual std::string sound() const { return "..."; }
  std::string speak() const { return name_ + " says " + sound(); }

 private:
  std::string name_;
};

class Dog : public Animal {
 public:
  using Animal::Animal;
  std::string sound() const override { return "Woof"; }
};

class Cat : public Animal {
 public:
  using Animal::Animal;
  std::string sound() const override { return "Meow"; }
};

int main() {
  std::vector<std::unique_ptr<Animal>> animals;
  animals.push_back(std::make_unique<Dog>("Rex"));
  animals.push_back(std::make_unique<Cat>("Tom"));
  animals.push_back(std::make_unique<Animal>("Generic"));

  for (const auto& animal : animals) {
    std::cout << animal->speak() << "\n";
  }

  Animal sliced = *animals[0];
  std::cout << "sliced copy: " << sliced.speak() << "\n";
}
Read the full lesson