C++ Programming: Objects, RAII and the STL ยท Inheritance and Polymorphism

Abstract Classes and Pure Virtual Functions

A pure virtual function (= 0) makes a class abstract. Children fill it in; shared code calls it.

abstract_classes.cpp

#include <iostream>
#include <string>
using namespace std;

class Animal {
public:
    virtual string sound() const = 0;      // pure virtual: no body here
    string speak() const { return "It says " + sound(); }
    virtual ~Animal() {}
};

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

class Cow : public Animal {
public:
    string sound() const override { return "moo"; }
};

int main() {
    Cat c;
    Cow w;
    const Animal *zoo[2] = {&c, &w};
    string first = zoo[0]->speak();
    string second = zoo[1]->speak();
    cout << first << " / " << second << endl;
    return 0;
}

Step by step

  1. c is created on the stack with the value {}.
  2. w is created on the stack with the value {}.
  3. An array of base pointers to different animals.
  4. speak() is shared code; it calls the virtual sound().
  5. C++ calls sound[abi:cxx11](). It gets its own variables on the stack.
  6. speak[abi:cxx11]() has finished, so its variables are gone. sound[abi:cxx11]() has finished, so its variables are gone. The value it returned, "It says meow", is stored in first.
  7. The same speak(), now for a Cow.
  8. C++ calls sound[abi:cxx11](). It gets its own variables on the stack.
  9. speak[abi:cxx11]() has finished, so its variables are gone. sound[abi:cxx11]() has finished, so its variables are gone. The value it returned, "It says moo", is stored in second.
  10. It prints It says meow / It says moo.
  11. The method returns 0.
  12. The destructor ~Cow() runs, because the object is going away.
  13. The destructor ~Animal() runs, because the object is going away.
  14. The destructor ~Cat() runs, because the object is going away. ~Cow() has finished, so its variables are gone. ~Animal() has finished, so its variables are gone.
  15. The destructor ~Animal() runs, because the object is going away.
  16. "It says meow / It says moo".