Inheritance and polymorphism
Reusing a base class, then calling the right override through a base reference — what virtual really costs, and the diamond problem.
- Derive a class and call the base constructor from it
- Explain static versus dynamic dispatch, and the vtable behind virtual
- Recognise the diamond problem and how virtual inheritance solves it
24inheritance.cpp derives one struct from another:
struct Derived1 : Base {
int z;
Derived1(int new_x, int new_y, int new_z) : Base(new_x, new_y), z(new_z) {}
};
A Derived1 is a Base with an extra member: it has x, y and z, can call print_x_y(), and its constructor hands x and y to the base constructor in the initialiser list.
Calling through a base reference
The point of inheritance is usually to treat different types the same way. 25polymorphism.cpp has a Dog and a Cat that both derive from Animal and both define speak():
Dog d; d.speak(); // Woof!
Cat c; c.speak(); // Meow!
Animal &a1 = d; a1.speak(); // Default speak function!
Animal &a2 = c; a2.speak(); // Default speak function!
Through an Animal&, both print the base version. Without virtual, the call is resolved at compile time from the static type of the expression — Animal — whatever object it really refers to.
25virtual_functions.cpp adds one keyword, virtual void speak(), and the last two lines become Woof! and Meow!. Now the call is resolved at run time from the dynamic type of the object.
What virtual costs
Each object of a class with virtual functions carries a hidden pointer, the vptr, to its class’s vtable — a table of function addresses. With g++ 13 on x86-64, sizeof(Animal) is 1 byte without virtual (an empty struct) and 8 with it. A virtual call is one extra load and an indirect jump, and the compiler can no longer inline it. For a speak() that prints, irrelevant; for a function called a billion times in an inner loop, worth knowing.
Two keywords make this safer:
-
override(as onDog::speak) asks the compiler to check that the function really overrides a virtual one. A typo such asspeek()then becomes an error instead of a silent new function.Cat::speakomits it and still works, but gets no such check. -
= 0makes a function pure virtual, as in26abstract_class.cpp.Animalthen becomes abstract: it cannot be instantiated, only derived from.
One rule the snake game follows and these examples do not need yet: a base class used polymorphically should have a virtual destructor (State.hpp declares virtual ~State()), so that deleting a derived object through a base pointer runs the derived destructor.
The diamond
29virtual_inheritance.cpp builds D from B and C, which both derive from A:
With plain inheritance, a D contains two separate A sub-objects, and A &a = d; does not compile: g++ reports that 'A' is an ambiguous base of 'D' (and the constructors print A, B, A, C, D). Declaring B : virtual A and C : virtual A makes them share one A; the program compiles and prints Constructing A!, B!, C!, D! — the shared base is built exactly once, before everything else.
Try it yourself. Store a Dog and a Cat in std::vector<std::unique_ptr<Animal>> and call speak() in a loop. Then remove virtual and predict the output before running. Finally print sizeof(Dog) with and without virtual.