Show contents
Chapter 4 of 6 · 20 min
Inheritance and virtual functions
By the end of this chapter, you'll be able to
- Define a base class with virtual functions and a virtual destructor
- Override a virtual function in a derived class with override
- Make a class abstract with a pure virtual function
- Store objects of different types in a vector of unique_ptr
A base, some derived classes
A derived class inherits the members of its base class. A function marked virtual can be overridden in derived classes. When you call it through a pointer or reference to the base, C++ picks the version of the object's real type, at run time: that's polymorphism.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class Vehicle {
public:
explicit Vehicle(std::string plate) : plate_(std::move(plate)) {}
virtual ~Vehicle() = default;
virtual double cost_per_km() const = 0; // pure virtual: abstract class
virtual std::string type() const = 0;
double trip_cost(double km) const { return km * cost_per_km(); }
const std::string& plate() const { return plate_; }
private:
std::string plate_;
};
class Car : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.25; }
std::string type() const override { return "car"; }
};
class Truck : public Vehicle {
public:
Truck(std::string plate, double load_t) : Vehicle(std::move(plate)), load_t_(load_t) {}
double cost_per_km() const override { return 0.60 + 0.05 * load_t_; }
std::string type() const override { return "truck"; }
private:
double load_t_;
};
class Bike : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.0; }
std::string type() const override { return "bike"; }
};
int main() {
std::vector<std::unique_ptr<Vehicle>> fleet;
fleet.push_back(std::make_unique<Car>("AB-123"));
fleet.push_back(std::make_unique<Truck>("CD-456", 8));
fleet.push_back(std::make_unique<Bike>("V-07"));
double total = 0;
for (const auto& v : fleet) {
double c = v->trip_cost(120);
std::cout << v->type() << " " << v->plate() << ": " << c << '\n';
total += c;
}
std::cout << "total: " << total << '\n';
}
car AB-123: 30
truck CD-456: 120
bike V-07: 0
total: 150
Let's break it down:
class Car : public Vehicle:Carinherits fromVehicle.publicmeans the base's public members stay public.= 0makes a function pure virtual: the base doesn't define it, and it becomes abstract. You can't create a plainVehicle, only cars, trucks or bikes.overridestates that you're overriding a virtual function of the base. If the signature doesn't match (a typo, a forgottenconst), the compiler refuses: withoutoverride, you'd silently create a new function.trip_costis written only once, in the base, and callscost_per_km(): each vehicle provides its own version.using Vehicle::Vehicle;reuses the base's constructor.std::vector<std::unique_ptr<Vehicle>>stores objects of different types. Theunique_ptrdestroys each vehicle at the end, calling the right destructor thanks to the base's virtual destructor.
The loop never tests the type: adding a Scooter would only mean writing its class.
Text description of the animation
- fleet contains a Car, a Truck and a Bike, all seen through unique_ptr<Vehicle>.
- trip_cost calls cost_per_km(). The object is a Car: its version runs. 120 × 0.25 = 30.
- Same line, different object: the Truck's version computes 1.0 per km, so 120.
- For the bike, the cost is zero.
- The loop never tests the type: adding a Scooter would only mean writing its class.
When to inherit?
Inheritance expresses an "is a" relationship: a truck is a vehicle, and it can be used anywhere a vehicle is expected. If the relationship is rather "has a" (a fleet has vehicles, a vehicle has an engine), use an attribute: that's composition, more flexible. A deep class hierarchy quickly becomes hard to evolve: prefer simple, abstract bases, with few levels.
Your turn
Worked exercise
Worked exercise: the cheapest vehicle
Add a Scooter class whose cost per kilometre is 0.08. Then write a function const Vehicle& cheapest(const std::vector<std::unique_ptr<Vehicle>>& fleet, double km) that returns the cheapest motorised vehicle (cost per kilometre strictly positive) for that trip. With a car, an 8-tonne truck, a bike and a scooter, the scooter must win for 50 km.
Hint 1
std::min_element(begin, end, comparison), from <algorithm>, returns an iterator to the smallest element according to your comparison function.Hint 2
Show the solution and common mistakes
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class Vehicle {
public:
explicit Vehicle(std::string plate) : plate_(std::move(plate)) {}
virtual ~Vehicle() = default;
virtual double cost_per_km() const = 0;
double trip_cost(double km) const { return km * cost_per_km(); }
const std::string& plate() const { return plate_; }
private:
std::string plate_;
};
class Car : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.25; }
};
class Truck : public Vehicle {
public:
Truck(std::string plate, double load_t) : Vehicle(std::move(plate)), load_t_(load_t) {}
double cost_per_km() const override { return 0.60 + 0.05 * load_t_; }
private:
double load_t_;
};
class Bike : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.0; }
};
class Scooter : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.08; }
};
const Vehicle& cheapest(const std::vector<std::unique_ptr<Vehicle>>& fleet, double km) {
auto it = std::min_element(fleet.begin(), fleet.end(), [km](const auto& a, const auto& b) {
bool a_free = a->cost_per_km() <= 0;
bool b_free = b->cost_per_km() <= 0;
if (a_free != b_free) return b_free; // a motorised vehicle comes before a free one
return a->trip_cost(km) < b->trip_cost(km);
});
return **it;
}
int main() {
std::vector<std::unique_ptr<Vehicle>> fleet;
fleet.push_back(std::make_unique<Car>("AB-123"));
fleet.push_back(std::make_unique<Truck>("CD-456", 8));
fleet.push_back(std::make_unique<Bike>("V-07"));
fleet.push_back(std::make_unique<Scooter>("SC-11"));
const Vehicle& v = cheapest(fleet, 50);
std::cout << "cheapest: " << v.plate() << " (" << v.trip_cost(50) << ")\n";
}
cheapest: SC-11 (4)
**it dereferences twice: the iterator gives the unique_ptr, and the unique_ptr gives the vehicle. We return a reference: the vehicle stays owned by the fleet.
Common mistakes:
- Returning a
Vehicleby value: impossible here, since the class is abstract. And even if it weren't, the object would be sliced and lose its scooter nature. - Calling
cheapeston an empty fleet:min_elementthen returnsend(), which must not be dereferenced. A real function would check this case, for example by throwing an exception.
Summary
- 1A virtual function called through the base runs the version of the object's real type.
- 2override has the compiler check that you really are overriding a virtual function.
- 3A pure virtual function (= 0) makes the class abstract.
- 4Every polymorphic class has a virtual destructor.
- 5A vector of unique_ptr<Base> stores objects of different types and destroys them correctly.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.