C++ Programming: Objects, RAII and the STL ยท Inheritance and Polymorphism
A pure virtual function (= 0) makes a class abstract. Children fill it in; shared code calls it.
#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;
}c is created on the stack with the value {}.w is created on the stack with the value {}.sound[abi:cxx11](). It gets its own variables on the stack.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.sound[abi:cxx11](). It gets its own variables on the stack.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.It says meow / It says moo.0.~Cow() runs, because the object is going away.~Animal() runs, because the object is going away.~Cat() runs, because the object is going away. ~Cow() has finished, so its variables are gone. ~Animal() has finished, so its variables are gone.~Animal() runs, because the object is going away.