These are the notes for C++ episode 16. Episode 15 ended with a list of Person* that called Person::show() for everyone, even for a Student and a Teacher that had their own show(). Here you will see why that happens (static binding), fix it with one word, virtual (dynamic binding), and look inside the machine (the vtable and vptr). Then you will guard your overrides with override, turn a meaningless base version into a pure virtual function (which makes the class abstract), add a brand-new type without editing any old code, and fix a hidden leak with a virtual destructor. The mini project is a shop checkout with UPI and card payments. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
The problem: a ride app and the if-chain trap
We're building a ride app. Each ride type has its own price for the same trip:
| Ride | Base fare | Per km | 5 km trip |
|---|---|---|---|
| Bike | ₹10 | ₹8 | ₹50 |
| Rickshaw | ₹25 | ₹12 | ₹85 |
| Cab | ₹50 | ₹18 | ₹140 |
| EBike (added next month) | ₹0 | ₹5 | ₹25 |
The obvious way: store the kind as text, and check it in an if-chain.
#include <iostream>
#include <string>
using namespace std;
class Ride {
public:
string kind;
double km;
Ride(string k, double d) : kind(k), km(d) {}
};
double fare(const Ride& r) {
if (r.kind == "bike") return 10 + 8 * r.km;
if (r.kind == "rickshaw") return 25 + 12 * r.km;
if (r.kind == "cab") return 50 + 18 * r.km;
return 0;
}
int main() {
Ride rides[4] = {{"bike", 5}, {"rickshaw", 5}, {"cab", 5}, {"ebike", 5}};
for (int i = 0; i < 4; i++)
cout << rides[i].kind << ": " << fare(rides[i]) << endl;
return 0;
}
Output:
bike: 50
rickshaw: 85
cab: 140
ebike: 0
Why it failed: nobody told fare() about "ebike", so it fell through to return 0: free rides, and no error anywhere. The fare function has to know every type. A real app has dozens of these chains (fare, arrival time, icon, number of seats), and every new type means finding and editing all of them. Miss one, and you get a silent bug like this.
Inheritance alone isn't enough (static binding)
Last episode's tool was inheritance: a base Ride with a fare, and children that write their own.
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
double fare() const { return 0; }
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const { return 10 + 8 * km; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() const { return 50 + 18 * km; }
};
int main() {
Bike b(5); Cab c(5);
Ride* rides[2] = {&b, &c};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
Output:
0
0
The same problem as episode 15. rides[i] is a Ride*, so while compiling, C++ decided to call Ride::fare(). It never looked at what the pointer really points to. Choosing the function from the pointer's (or reference's) declared type at compile time is called static binding (or early binding).
The fix: virtual (dynamic binding)
Real-life example: asking for the fare.
| In the app | In C++ |
|---|---|
| The app asks every vehicle the same question: "your fare?", without caring which vehicle it is | one call: rides[i]->fare() |
| Each driver answers with their own rate card | virtual double fare(): the real object's version runs |
| EBike drivers join, and the app is not changed | class EBike : public Ride: just a new class |
Put the word virtual before fare in the base class. Nothing else changes:
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const { return 10 + 8 * km; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() const { return 50 + 18 * km; }
};
int main() {
Bike b(5); Cab c(5);
Ride* rides[2] = {&b, &c};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
Output:
50
140
virtual tells C++: don't decide while compiling. When the program runs, look at the real object and call its version. That's dynamic binding (late binding). One call, many forms of answer: that's polymorphism (Greek for "many forms"). This kind, chosen at run time through a base pointer or reference, is run-time polymorphism. (Function overloading from episode 7 is sometimes called compile-time polymorphism.)
Bike::fare()andCab::fare()are overrides: a child's version of a virtual function with exactly the same signature (name, parameters, andconst).- A function stays virtual in every child, even if the child doesn't write
virtualagain. - Dynamic binding only happens through a pointer or a reference to the base. Calling on an object directly (
c.fare()) just uses that object's class.
How it works inside: vtable and vptr
Real-life example: each vehicle carries a rate card.
| Real life | In C++ |
|---|---|
| A rate card in every type of vehicle (Bike's card, Cab's card) | the vtable: one table of function addresses per class |
| The driver shows their card and the app reads it | the hidden vptr: a pointer inside every object, pointing to its class's vtable |
| Reading the card takes a moment | one extra lookup per virtual call |
For each class with virtual functions, the compiler builds a small table, the vtable: "for this class, fare is this function". Every object of such a class secretly carries a pointer to its class's table, the vptr. So rides[i]->fare() means: follow the object's vptr, look up fare, call it.
You can see the hidden pointer in the object's size:
#include <iostream>
using namespace std;
class A { public: virtual void f() {} };
class B : public A {};
class C { public: void f() {} };
int main(){ cout << sizeof(A) << " " << sizeof(C) << endl; }
Output (64-bit Linux):
8 1
C has no data and no virtual functions, so it takes 1 byte (an object can't have size 0). A has a virtual function, so every A carries an 8-byte vptr. That memory, plus one extra lookup per call, is why C++ doesn't make every function virtual automatically: you choose. (The vtable is how g++, Clang and MSVC implement virtual functions; the C++ standard only describes the behaviour.)
The override keyword
A sneaky bug: someone edits Cab::fare() and forgets the const at the end.
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const { return 10 + 8 * km; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() { return 50 + 18 * km; }
};
int main() {
Bike b(5); Cab c(5);
Ride* rides[2] = {&b, &c};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
Output:
50
0
No error, no warning. Without const, double fare() is a different function: it doesn't override Ride::fare() const, it just sits next to it (it hides it). Through a Ride*, the base version runs and the cab charges zero again. You can see both functions exist:
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() { return 50 + 18 * km; }
};
int main() {
Cab c(5);
Ride* r = &c;
cout << "through Ride*: " << r->fare() << endl;
cout << "direct: " << c.fare() << endl;
return 0;
}
Output:
through Ride*: 0
direct: 140
The guard: write override after every child version. Then, if it doesn't really override a virtual function, the compiler must refuse:
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const { return 10 + 8 * km; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() override { return 50 + 18 * km; }
};
int main() {
Bike b(5); Cab c(5);
Ride* rides[2] = {&b, &c};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
main.cpp:20:12: error: 'double Cab::fare()' marked 'override', but does not override
Put the const back (double fare() const override) and it compiles and prints 50 and 140:
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const { return 10 + 8 * km; }
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() const override { return 50 + 18 * km; }
};
int main() {
Bike b(5); Cab c(5);
Ride* rides[2] = {&b, &c};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
Output:
50
140
Rule: always write override on a child's version of a virtual function. It costs nothing and turns silent bugs into compile errors.
Pure virtual functions and abstract classes
Ride::fare() returning 0 is not a real fare. A plain "Ride" shouldn't exist at all, only bikes, cabs and so on. So we say: Ride has a fare, but no body. Write = 0 instead of a body:
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const = 0;
};
int main() {
Ride x(5);
cout << x.fare() << endl;
return 0;
}
main.cpp:14:10: error: cannot declare variable 'x' to be of abstract type 'Ride'
main.cpp:5:7: note: because the following virtual functions are pure within 'Ride':
main.cpp:10:20: note: 'virtual double Ride::fare() const'
- A virtual function with
= 0is a pure virtual function. - A class with at least one pure virtual function is an abstract class: only a plan for children. You can't create an object of it, but you can have
Ride*andRide&pointing at its children. - A class that is not abstract (you can create objects of it) is called a concrete class.
A child must write every pure virtual function, or it is abstract too. Here's an EBike that forgot fare():
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const = 0;
};
class EBike : public Ride {
public:
EBike(double d) : Ride(d) {}
};
int main() {
EBike e(5);
return 0;
}
main.cpp:18:11: error: cannot declare variable 'e' to be of abstract type 'EBike'
main.cpp:12:7: note: because the following virtual functions are pure within 'EBike':
main.cpp:10:20: note: 'virtual double Ride::fare() const'
Forgetting fare() is now impossible. (An abstract class with only pure virtual functions and no data is what other languages call an interface.)
Adding a new type without touching old code
Now the real test of the design. Add EBike, ₹5 per km. (The video shows Bike and the new EBike to keep it on one screen; Cab works the same way.)
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const = 0;
};
class Bike : public Ride {
public:
Bike(double d) : Ride(d) {}
double fare() const override { return 10 + 8 * km; }
};
class EBike : public Ride {
public:
EBike(double d) : Ride(d) {}
double fare() const override { return 5 * km; }
};
int main() {
Bike b(5); EBike e(5);
Ride* rides[2] = {&b, &e};
for (int i = 0; i < 2; i++)
cout << rides[i]->fare() << endl;
return 0;
}
Output:
50
25
Compare that with the if-chain: there, a new type meant editing every chain in the app. Here, it's one new class, and the loop that already existed works with it without being touched. Code that is open to new types but closed to edits is the open/closed principle.
Virtual destructors
From episode 13: a Cab rents memory for its GPS log in its constructor and frees it in its destructor. main creates a cab with new, keeps it in a Ride*, and deletes it:
#include <iostream>
#include <string>
using namespace std;
class Ride {
public:
~Ride() { cout << "Ride gone" << endl; }
};
class Cab : public Ride {
int* gps;
public:
Cab() : gps(new int[1000]) {}
~Cab() { delete[] gps; cout << "Cab gone, GPS freed" << endl; }
};
int main() {
Ride* r = new Cab();
delete r;
return 0;
}
Output:
Ride gone
~Cab() never ran, so the GPS memory leaked. The destructor isn't virtual, so delete r looked only at the pointer's type, Ride. The C++ standard says deleting a derived object through a base pointer whose destructor is not virtual is undefined behaviour: anything may happen, and here it skipped ~Cab().
Fix: make the base destructor virtual.
#include <iostream>
#include <string>
using namespace std;
class Ride {
public:
virtual ~Ride() { cout << "Ride gone" << endl; }
};
class Cab : public Ride {
int* gps;
public:
Cab() : gps(new int[1000]) {}
~Cab() { delete[] gps; cout << "Cab gone, GPS freed" << endl; }
};
int main() {
Ride* r = new Cab();
delete r;
return 0;
}
Output:
Cab gone, GPS freed
Ride gone
Child first, then parent, as in episode 15. Rule: if a class has any virtual function (it's meant to be used through a base pointer), give it a virtual destructor. An empty one is fine: virtual ~Ride() {}.
Object slicing: why it must be a pointer or a reference
Dynamic binding works through a Ride* or a Ride&. If you pass a Cab by value as a Ride, only the Ride part is copied: the Cab part is "sliced off", and the copy really is a plain Ride.
#include <iostream>
#include <string>
using namespace std;
class Ride {
protected:
double km;
public:
Ride(double d) : km(d) {}
virtual double fare() const { return 0; }
virtual ~Ride() {}
};
class Cab : public Ride {
public:
Cab(double d) : Ride(d) {}
double fare() const override { return 50 + 18 * km; }
};
void byValue(Ride r) { cout << "by value: " << r.fare() << endl; }
void byRef(const Ride& r) { cout << "by reference: " << r.fare() << endl; }
int main() {
Cab c(5);
byValue(c);
byRef(c);
return 0;
}
Output:
by value: 0
by reference: 140
This is object slicing. Pass polymorphic objects as const Ride& or Ride*. (Making the base abstract also prevents it: you can't pass an abstract type by value.)
Polymorphism rules
virtualin the base → the real object's version runs.- It works through a pointer or a reference:
Ride*/Ride&(a copy is just aRide). - Child versions: always write
override. - No sensible base body?
= 0→ abstract class. - Any virtual function → virtual destructor.
| Static binding | Dynamic binding | |
|---|---|---|
| Decided | at compile time | at run time |
| Decided by | the pointer's / reference's declared type | the real object's type |
| Needs | nothing (default) | virtual, called through a pointer or reference |
| Cost | none | a vptr in each object, one lookup per call |
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
Forgetting virtual in the base |
double fare() const { return 0; } |
no message: Ride::fare() runs for every object (0, 0) |
virtual double fare() const |
A child version that doesn't match (missing const), without override |
double fare() { ... } |
no message: the base version runs (50, 0) |
double fare() const override |
The same, with override |
double fare() override { ... } |
error: 'double Cab::fare()' marked 'override', but does not override |
match the signature exactly, including const |
| Creating an object of an abstract class | Ride x(5); with fare() = 0 |
error: cannot declare variable 'x' to be of abstract type 'Ride' |
create a Bike, Cab, ... |
| A child that doesn't implement a pure virtual function | EBike without fare() |
error: cannot declare variable 'e' to be of abstract type 'EBike' with note: because the following virtual functions are pure within 'EBike' |
write double fare() const override |
| A non-virtual base destructor, deleted through a base pointer | delete r; with ~Ride() |
no message: only Ride gone, ~Cab() skipped, memory leaked (undefined behaviour) |
virtual ~Ride() |
| Passing a child by value as the base | void byValue(Ride r) |
no message: sliced, prints 0 |
const Ride& |
Mini project: a shop checkout
Payment is abstract: a pure virtual total(amount), and a virtual destructor because it's a base class. UPI has no fee; a card adds 2%. main reads a payment type and an amount again and again, creates the right payment with new, prints its total through the Payment*, and deletes it.
#include <iostream>
#include <string>
using namespace std;
class Payment {
public:
virtual double total(double amt) const = 0;
virtual ~Payment() {}
};
class Upi : public Payment {
public:
double total(double amt) const override { return amt; }
};
class Card : public Payment {
public:
double total(double amt) const override { return amt * 1.02; }
};
int main() {
string type; double a;
while (cin >> type >> a) {
Payment* p;
if (type == "upi") p = new Upi();
else p = new Card();
cout << type << ": " << p->total(a) << endl;
delete p;
}
return 0;
}
Input:
upi 500
card 1000
upi 250
Output:
upi: 500
card: 1020
upi: 250
The type is checked only once, when the payment is created. After that, the code only talks to Payment. Adding wallet payments tomorrow means one new class.
Extend it: add cash on delivery (Cod, amount + ₹40) and a running total (practice question 1).
Practice
- Add
Cod(cash on delivery: amount + 40) to the checkout, and print the total of all payments at the end. - Shapes: an abstract
Shapewith pure virtualarea()andname(), thenCircleandRect. Print each area and the total, through aShape*list. - Fix last episode's
Personlist so each person uses its ownshow(). - In the
overrideexample, remove bothoverrideand theconstfromCab::fare(). What prints, and why?
Solution
1. One new class, one new else if, and a sum.
#include <iostream>
#include <string>
using namespace std;
class Payment {
public:
virtual double total(double amt) const = 0;
virtual ~Payment() {}
};
class Upi : public Payment {
public:
double total(double amt) const override { return amt; }
};
class Card : public Payment {
public:
double total(double amt) const override { return amt * 1.02; }
};
class Cod : public Payment {
public:
double total(double amt) const override { return amt + 40; }
};
int main() {
string type; double a, sum = 0;
while (cin >> type >> a) {
Payment* p;
if (type == "upi") p = new Upi();
else if (type == "card") p = new Card();
else p = new Cod();
cout << type << ": " << p->total(a) << endl;
sum += p->total(a);
delete p;
}
cout << "Total: " << sum << endl;
return 0;
}
Input:
upi 500
card 1000
cod 300
Output:
upi: 500
card: 1020
cod: 340
Total: 1860
2. Two pure virtual functions; both children must write both.
#include <iostream>
#include <string>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
virtual string name() const = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
double r;
public:
Circle(double radius) : r(radius) {}
double area() const override { return 3.14159 * r * r; }
string name() const override { return "Circle"; }
};
class Rect : public Shape {
double w, h;
public:
Rect(double a, double b) : w(a), h(b) {}
double area() const override { return w * h; }
string name() const override { return "Rect"; }
};
int main() {
Circle c(2);
Rect r(3, 4);
Shape* shapes[2] = {&c, &r};
double total = 0;
for (int i = 0; i < 2; i++) {
cout << shapes[i]->name() << ": " << shapes[i]->area() << endl;
total += shapes[i]->area();
}
cout << "Total area: " << total << endl;
return 0;
}
Output:
Circle: 12.5664
Rect: 12
Total area: 24.5664
3. Make show() virtual in Person (and give it a virtual destructor), and mark the children's versions override.
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person(string n, int a) : name(n), age(a) {}
virtual void show() const { cout << name << ", " << age << endl; }
virtual ~Person() {}
};
class Student : public Person {
int roll;
public:
Student(string n, int a, int r) : Person(n, a), roll(r) {}
void show() const override { cout << "Student, roll " << roll << endl; }
};
class Teacher : public Person {
public:
Teacher(string n, int a) : Person(n, a) {}
void show() const override { cout << "Teacher" << endl; }
};
int main() {
Student s("Aman", 18, 7);
Teacher t("Neha", 18);
Person* list[2] = {&s, &t};
for (int i = 0; i < 2; i++) list[i]->show();
return 0;
}
Output:
Student, roll 7
Teacher
4. It compiles with no message and prints 50 then 0: without const, Cab::fare() is a different function that doesn't override Ride::fare() const, so the Ride* calls the base version. That's exactly the bug override catches (the first example in the override section).
Quick quiz
What does this print?
#include <iostream>
#include <string>
using namespace std;
class A {
public:
virtual void f() { cout << "A"; }
void g() { cout << "a"; }
};
class B : public A {
public:
void f() override { cout << "B"; }
void g() { cout << "b"; }
};
int main() {
B x;
A* p = &x;
p->f(); p->g();
return 0;
}
- A.
AB - B.
Ba - C.
Bb - D.
Aa
Answer
B: Ba (verified). f is virtual, so p->f() runs the real object's version: B. g is not virtual, so p->g() is decided by the pointer's type, A*: a.
Interview questions
- What is polymorphism? One interface, many forms: the same call (
r->fare()) does the right thing for each type of object. In C++, run-time polymorphism uses virtual functions through base pointers or references; compile-time polymorphism uses overloading and templates. - What is a virtual function? A member function declared with
virtualin a base class, so that calls through a base pointer or reference run the most-derived override of the real object. - Static vs dynamic binding? Static (early) binding chooses the function at compile time from the declared type; dynamic (late) binding chooses it at run time from the object's real type. Non-virtual calls are static; virtual calls through a pointer/reference are dynamic.
- How are virtual functions implemented? Typically with a vtable per class (a table of function addresses) and a hidden vptr in each object pointing to its class's vtable. A virtual call loads the vptr, indexes the table and calls through it.
- What does
overridedo? It asks the compiler to check that the function really overrides a base virtual function; if the signature doesn't match, it's an error (marked 'override', but does not override). - What is a pure virtual function? An abstract class?
virtual T f() = 0;has no implementation in that class. A class with at least one is abstract: it can't be instantiated, and concrete children must implement every pure virtual function. - Why does a base class need a virtual destructor? Deleting a derived object through a base pointer with a non-virtual destructor is undefined behaviour; in practice the derived destructor is skipped and its resources leak.
- What is object slicing? Copying a derived object into a base object by value keeps only the base part, so virtual calls on the copy use the base version.
- Can a constructor be virtual? No. While constructing, the object's type isn't complete yet; the vptr is set up as each constructor runs. (Destructors can and often should be virtual.)
- Difference between overloading and overriding? Overloading: same name, different parameters, in the same scope, chosen at compile time. Overriding: same signature in a derived class, replacing a virtual function, chosen at run time.
- What is the cost of virtual functions? One vptr per object (8 bytes on 64-bit) and an indirect call, which also usually stops the compiler from inlining.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Polymorphism | "Many forms": one call that behaves correctly for each type of object | rides[i]->fare() |
| Run-time polymorphism | Polymorphism decided while the program runs, through virtual functions | the Ride* loop |
| Compile-time polymorphism | Choosing a function while compiling, e.g. overloading (episode 7) | area(int) vs area(double) |
| If-chain on a type | Code that checks a "kind" value to decide what to do | if (r.kind == "bike") ... |
| Static binding | The function is chosen at compile time from the declared type | non-virtual fare() → 0, 0 |
| Dynamic binding | The function is chosen at run time from the real object | virtual fare() → 50, 140 |
| Virtual function | A base-class function marked virtual, so children's versions run through base pointers |
virtual double fare() const |
| Override | A child's version of a virtual function with exactly the same signature | Cab::fare() const |
override |
A keyword asking the compiler to check that it really overrides | double fare() const override |
| Signature | A function's name, parameter types and qualifiers like const |
fare() const |
| Hiding | A child function with the same name but a different signature hides the base one instead of overriding | double fare() without const |
| vtable | A table of function addresses the compiler makes for each class with virtual functions | Cab's table: fare → Cab::fare |
| vptr | A hidden pointer inside each object, pointing to its class's vtable | why sizeof(A) is 8 |
| Pure virtual function | A virtual function with = 0 and no body in that class |
virtual double fare() const = 0; |
| Abstract class | A class with at least one pure virtual function; can't be instantiated | Ride, Payment, Shape |
| Concrete class | A class you can create objects of | Bike, Upi |
| Interface | An abstract class with only pure virtual functions | Payment |
| Virtual destructor | A base destructor marked virtual, so delete through a base pointer runs the child's destructor too |
virtual ~Ride() |
| Undefined behaviour | Code the C++ standard gives no meaning to; anything may happen | delete through a base pointer without a virtual destructor |
| Memory leak | Memory rented with new but never returned |
the skipped ~Cab() |
| Object slicing | Copying a child into a base object by value; the child part is cut off | void byValue(Ride r) |
| Open/closed principle | Code open to new types (extension) but closed to edits | adding EBike without touching the loop |
Summary
- An if-chain on a type string must know every type; a new
"ebike"silently got fare0. - With plain inheritance, a
Ride*callsRide::fare()for everyone: static binding, decided at compile time. virtualmakes the real object's version run at run time: dynamic binding, the heart of polymorphism. Inside, a vtable per class and a vptr per object.- A child version with a different signature (a missing
const) silently doesn't override.overrideturns that intoerror: ... marked 'override', but does not override. = 0makes a pure virtual function; the class becomes abstract (cannot declare variable 'x' to be of abstract type 'Ride'), and children must implement it.- New types plug in as one new class, with no edits to existing code.
- A base class needs a virtual destructor, or
deletethrough a base pointer skips the child's destructor. - Use pointers or references: passing by value slices the object.
Next episode: operator overloading. Our classes can now be extended without editing old code. Next: make a + b, a == b and cout << a work for your own classes.