Abstract Classes and Virtual Functions
Lesson 18 of 20Shapes that refuse to be built — pure virtual methods force every child class to earn its concrete form.
Contracts, not objects
An abstract class is a promise: "every child of mine will know how to do this." It never runs itself.
Abstract class
Has at least one pure virtual method — you cannot create objects of it, only point at its children.
Pure virtual: = 0
virtual void draw() = 0; has no body. It says: children must implement this, no exceptions.
Concrete child
A child that implements every pure virtual becomes buildable — Circle can finally exist.
Why bother?
The base defines WHAT every child must do; each child decides HOW. Mistakes fail at compile time.
A Shape that cannot be built
Press play — Shape stays on paper, while Circle and Square are concrete enough to draw.
1#include <iostream>2class Shape {3public:4virtual void draw() = 0;5};6class Circle : public Shape {7public:8void draw() {9std::cout << "Draw a circle\n";10}11};12class Square : public Shape {13public:14void draw() {15std::cout << "Draw a square\n";16}17};18int main() {19Circle c;20Square s;21c.draw();22s.draw();23return 0;24}
The preprocessor pastes in iostream for cout.
Who may be built?
The compiler asks one question about every class in the chain: any pure virtual left?
Predict the output
A barn of Animal pointers — what does the loop print?
1#include <iostream>2class Animal {3public:4virtual void speak() = 0;5};6class Duck : public Animal {7public:8void speak() { std::cout << "Quack\n"; }9};10class Cow : public Animal {11public:12void speak() { std::cout << "Moo\n"; }13};14int main() {15Duck d;16Cow w;17Animal* barn[2] = { &d, &w };18for (int i = 0; i < 2; i = i + 1) {19barn[i]->speak();20}21return 0;22}
Hint: speak is pure virtual in Animal, so every child must supply its own; the loop dispatches on the real object.
Match the contract terms
Click a term, then click its description to lock the pair.
Key takeaways
One pure virtual method (= 0) makes the whole class abstract.
Abstract classes define WHAT; concrete children decide HOW.
You cannot build an abstract object — only point at child objects.
Forcing children to implement methods catches mistakes at compile time.
Pure virtual + base pointers = pluggable, extensible design.