Module 4 · Your own types
4.6Inheritance and virtual functions
Build a class on top of another, and call the right version of a function through a base reference or pointer. Learn virtual, override, final and abstract classes, why a base needs a virtual destructor, what slicing does, and how a virtual call works.
On this page
- Key terms
- In 30 seconds
- Deriving one class from another
- The base part is built first
- virtual: the object’s real type decides
- override catches mistakes
- final: no further changes
- Pure virtual functions and abstract classes
- Many layer types in one list
- The virtual destructor
- Composition and std::variant instead
- Which one should I use?
- Under the hood
- Common pitfalls
- Object slicing
- Deleting through a base with no virtual functions
- Try it yourself
Key terms
- inheritance
- Building a new class from an existing one. The new class gets all the members of the old one and can add its own.
- base class, derived class
- In
struct Relu : Layer,Layeris the base class andReluthe derived class. A derived object is also a base object, so it can be passed wherever a base is expected. - static type and dynamic type
- The static type is what the code says a reference or pointer refers to (
const Layer&). The dynamic type is the real type of the object there at run time (Relu). virtualfunction- A member function whose version is picked at run time, from the object's dynamic type, when you call it through a base reference or pointer.
- override,
override - To override is to give a derived class its own version of a base class's virtual function. Writing
overrideafter the function says that's what you mean; if it doesn't override anything, the code doesn't compile. - pure virtual function, abstract class
- A virtual function declared with
= 0instead of a body is pure virtual. A class with one is abstract: you can't create an object of it, only of derived classes that override it. - virtual destructor
- A destructor marked
virtual, so deleting a derived object through a base pointer runs the derived class's destructor too. - object slicing
- Copying a derived object into a base object by value. Only the base part is copied; the derived members and behavior are lost.
- vtable and vptr
- How GCC and Clang implement virtual calls: one table of function addresses per class (the vtable), and a hidden pointer to it in each object (the vptr).
Sometimes several types share a job but do it differently. Every layer in a small neural network takes a number and gives back a number, but a ReLU layer, a scaling layer and a sigmoid layer each compute something else. You’d like to keep them in one list and run them in order without caring which is which. Inheritance and virtual functions let you write that code once, against a common base class, and have each object run its own version.
In 30 seconds
struct Relu : Layer { … };makesRelua derived class ofLayer. It gets all ofLayer’s members, and aRelucan be passed wherever aconst Layer&orLayer*is expected.- Mark a base member function
virtual, and writeoverrideon each derived version. A call through a base reference or pointer then runs the version for the object’s real type. - A base class with virtual functions needs a
virtualdestructor, so deleting through a base pointer destroys the whole object. - Copying a derived object into a base object by value slices it. Hold derived objects through references, pointers or
std::unique_ptr<Base>.
Deriving one class from another
Write : public Base after a class’s name to build it on Base. The derived class gets every member of the base and adds its own. Here a Thermometer is a Sensor that also holds a reading:
#include <print>
#include <string>
class Sensor {
public:
explicit Sensor(const std::string& name) : name_{name} {}
const std::string& name() const { return name_; }
private:
std::string name_;
};
class Thermometer : public Sensor {
public:
explicit Thermometer(double celsius) : Sensor{"temp"}, celsius_{celsius} {}
double celsius() const { return celsius_; }
private:
double celsius_;
};
void report(const Sensor& sensor) {
std::println("sensor {}", sensor.name());
}
int main() {
Thermometer t{21.5};
std::println("{} reads {}", t.name(), t.celsius());
report(t);
}Output
temp reads 21.5 sensor temp
Three things to notice:
t.name()works becauseThermometerinherited it fromSensor.reporttakes aconst Sensor&, and aThermometeris accepted: a derived object is a base object, with extra parts.Thermometer’s constructor builds itsSensorpart by namingSensor{"temp"}in its member initializer list. It can’t setname_itself, becausename_is private toSensor. (Members markedprotectedwould be visible to derived classes but not to outside code; private data plus public functions is usually clearer.)
With class, write public before the base; leave it out and the inheritance is private, so outside code can’t treat a Thermometer as a Sensor. With struct, inheritance is public by default. The rest of this lesson uses struct to keep examples short.
The base part is built first
An object is built from the base up, whatever order you write the initializer list in, and destroyed in the opposite order, so the derived part never runs without its base:
#include <print>
struct Sensor {
Sensor() { std::println("Sensor part built"); }
~Sensor() { std::println("Sensor part destroyed"); }
};
struct Thermometer : Sensor {
Thermometer() { std::println("Thermometer part built"); }
~Thermometer() { std::println("Thermometer part destroyed"); }
};
int main() {
Thermometer t;
std::println("in use");
}Output
Sensor part built Thermometer part built in use Thermometer part destroyed Sensor part destroyed
virtual: the object’s real type decides
Now the network. A Layer passes its input through unchanged, and a Relu layer turns negative numbers into 0. Without virtual, a call through a const Layer& always runs Layer’s version, whatever the object really is:
#include <print>
struct Layer {
double forward(double x) const { return x; }
};
struct Relu : Layer {
double forward(double x) const { return x > 0 ? x : 0.0; }
};
void run(const Layer& layer, double x) {
std::println("{}", layer.forward(x));
}
int main() {
Relu relu;
std::println("{}", relu.forward(-2.0));
run(relu, -2.0);
}Output
0 -2
Inside run, the static type of layer, the type the code names, is Layer. The compiler picks the function from that. The dynamic type, the real type of the object at run time, is Relu, but a normal call ignores it.
Mark the base function virtual and the call is decided at run time from the dynamic type. Each derived class overrides it, and writes override to say so:
#include <print>
struct Layer {
virtual ~Layer() = default; // see "The virtual destructor" below
virtual double forward(double x) const { return x; }
};
struct Relu : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
};
struct Scale : Layer {
double factor;
explicit Scale(double f) : factor{f} {}
double forward(double x) const override { return x * factor; }
};
void run(const Layer& layer, double x) {
std::println("{}", layer.forward(x));
}
int main() {
Relu relu;
Scale twice{2.0};
run(relu, -2.0);
run(twice, -2.0);
}Output
0 -4
run was written once, against Layer, and each object runs its own forward. This is polymorphism. It works through references and pointers: const Layer&, Layer*, std::unique_ptr<Layer>.
Key ideavirtual goes in the base, override in the derived class
virtual in the base class makes the function overridable. In a derived class, write override and not virtual: a function that overrides a virtual one is virtual anyway, and override adds a check.
override catches mistakes
An overriding function must have the same name, parameter types and const as the base’s. Without override, a small slip makes a new, unrelated function, and the program compiles and quietly runs the base version. Here forward is misspelled:
#include <print>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const { return x; }
};
struct Relu : Layer {
double foward(double x) const { return x > 0 ? x : 0.0; }
};
void run(const Layer& layer, double x) {
std::println("{}", layer.forward(x));
}
int main() {
Relu relu;
run(relu, -2.0);
}Output
-2
Add override and the compiler checks that the function really replaces a virtual one in the base:
#include <print>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const { return x; }
};
struct Relu : Layer {
double foward(double x) const override { return x > 0 ? x : 0.0; }
};
int main() {
Relu relu;
std::println("{}", relu.forward(-2.0));
}The compiler rejects this
main.cpp:9:12: error: ‘double Relu::foward(double) const’ marked ‘override’, but does not override
9 | double foward(double x) const override { return x > 0 ? x : 0.0; }
| ^~~~~~A missing const or a different parameter type gets the same error. Write override on every overriding function.
final: no further changes
final after a class name stops anyone deriving from it. After a virtual function, it stops derived classes overriding that function again.
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const { return x; }
};
struct Relu final : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
};
struct LeakyRelu : Relu {};
int main() {}The compiler rejects this
main.cpp:10:8: error: cannot derive from ‘final’ base ‘Relu’ in derived type ‘LeakyRelu’
10 | struct LeakyRelu : Relu {};
| ^~~~~~~~~Pure virtual functions and abstract classes
A plain Layer that returns its input isn’t very useful. Often the base class has no sensible version of a function; it only says that every layer has one. Write = 0 instead of a body to make it a pure virtual function. A class with one is abstract: you can’t create an object of it.
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const = 0;
};
int main() {
Layer layer;
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:7:11: error: cannot declare variable ‘layer’ to be of abstract type ‘Layer’
7 | Layer layer;
| ^~~~~
main.cpp:1:8: note: because the following virtual functions are pure within ‘Layer’:
1 | struct Layer {
| ^~~~~
main.cpp:3:20: note: ‘virtual double Layer::forward(double) const’
3 | virtual double forward(double x) const = 0;
| ^~~~~~~A derived class that overrides every pure virtual function can be created. One that misses any is abstract too.
Many layer types in one list
A std::vector<Layer> can’t hold a Relu or a Scale: each element would be exactly a Layer, with room for nothing more (and now that Layer is abstract, there can’t be one at all). Store owning pointers to the base instead, std::unique_ptr<Layer> from Smart pointers. Each one points at a whole object of its own type on the heap:
#include <memory>
#include <print>
#include <string_view>
#include <vector>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const = 0;
virtual std::string_view name() const = 0;
};
struct Relu : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
std::string_view name() const override { return "relu"; }
};
struct Scale : Layer {
double factor;
explicit Scale(double f) : factor{f} {}
double forward(double x) const override { return x * factor; }
std::string_view name() const override { return "scale"; }
};
int main() {
std::vector<std::unique_ptr<Layer>> net;
net.push_back(std::make_unique<Scale>(-3.0));
net.push_back(std::make_unique<Relu>());
net.push_back(std::make_unique<Scale>(0.5));
double x = -2.0;
for (const auto& layer : net) {
x = layer->forward(x);
std::println("after {}: {}", layer->name(), x);
}
}Output
after scale: 6 after relu: 6 after scale: 3
The loop doesn’t know or care which layers it runs. A new layer type works without changing it.
The virtual destructor
When net goes out of scope, each unique_ptr<Layer> deletes its object through a Layer*. For that to destroy a Scale properly, Layer’s destructor must be virtual, so the call goes to the destructor for the dynamic type. That’s what virtual ~Layer() = default; is for.
Leave it out and deleting a derived object through a base pointer is undefined behavior. In practice, the derived destructor doesn’t run, so the derived members are never cleaned up, and the memory is freed as if it held only the smaller base object. When the base has virtual functions, both compilers warn, and with warnings as errors it doesn’t compile:
struct Layer {
~Layer() = default;
virtual double forward(double x) const { return x; }
};
struct Scale : Layer {
double factor = 2.0;
double forward(double x) const override { return x * factor; }
};
int main() {
Layer* layer = new Scale;
delete layer;
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:13:5: error: deleting object of polymorphic class type ‘Layer’ which has non-virtual destructor might cause undefined behavior [-Werror=delete-non-virtual-dtor]
13 | delete layer;
| ^~~~~~~~~~~~
cc1plus: all warnings being treated as errorsThe fix is one line in the base: virtual ~Layer() = default;.
Common pitfallEvery base with virtual functions gets a virtual destructor
If a class has any virtual function, it’s meant to be used through base pointers, so give it virtual ~Base() = default;. The compilers can’t always see the mistake: Common pitfalls shows a case they miss.
Composition and std::variant instead
Inheritance ties classes together tightly, and polymorphism usually means heap objects behind pointers. Two other tools often fit better.
Composition: when you want to reuse a type’s data or functions, hold it as a member. A scored read has a read, and nothing needs to treat it as one, so struct ScoredRead { Read read; std::vector<double> scores; }; is all it takes, the same as any struct from Structs and classes. You reach the read’s fields as r.read.id.
std::variant: when the list of types is fixed and known when you write the code, store a std::variant by value. No base class, no virtual, no heap, and the elements sit next to each other in the vector. std::visit calls the right forward for whichever type each element holds. The visitor is a lambda with an auto parameter, as in that lesson: const auto& l accepts either layer type, and [x] lets the lambda read the local x. Lambdas covers them in full.
#include <print>
#include <variant>
#include <vector>
struct Relu {
double forward(double x) const { return x > 0 ? x : 0.0; }
};
struct Scale {
double factor;
double forward(double x) const { return x * factor; }
};
using Layer = std::variant<Relu, Scale>;
int main() {
std::vector<Layer> net = {Scale{-3.0}, Relu{}, Scale{0.5}};
double x = -2.0;
for (const Layer& layer : net) {
x = std::visit([x](const auto& l) { return l.forward(x); }, layer);
}
std::println("{}", x);
}Output
3
The trade: adding a new layer type means changing Layer, the variant, and the compiler then checks every std::visit handles it. With inheritance, anyone can add a type without touching the base.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
Inheritance with virtual | The set of types is open: new ones are added later, maybe by other people, and they all share one interface. | Code written against the base works with every derived type, including ones that don’t exist yet. | struct Relu : Layer, with override, held as std::unique_ptr<Layer> |
std::variant | The set of types is fixed and small, and you know them all now. | Values are stored directly, with no heap allocation and no virtual calls, and std::visit is checked against every type. | std::variant<Relu, Scale> and std::visit |
| Composition | You want another type’s data or functions, but nobody needs to treat your type as that type. | Members are simpler than a class hierarchy and keep the types independent. | struct ScoredRead { Read read; … }; |
Rule of thumb: reach for a member first, a std::variant for a fixed set of types, and inheritance with virtual when the set of types must stay open.
Under the hood
With GCC and Clang, a class with virtual functions gets one vtable: a table, built by the compiler and stored with the program’s read-only data, that holds the address of the class’s version of each virtual function. Each object of the class gets a hidden pointer, the vptr, set by its constructor to point at its class’s table. With single inheritance like this, that pointer is the only cost per object:
#include <print>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const = 0;
};
struct Relu : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
};
struct Scale : Layer {
double factor;
explicit Scale(double f) : factor{f} {}
double forward(double x) const override { return x * factor; }
};
struct PlainScale { // the same data, no virtual functions
double factor;
};
int main() {
Relu relu;
Scale twice{2.0};
Scale half{0.5};
std::println("Relu {}, Scale {}, PlainScale {}", sizeof(Relu),
sizeof(Scale), sizeof(PlainScale));
std::println("{}", relu.forward(half.forward(twice.forward(3.0))));
}Output
Relu 8, Scale 16, PlainScale 8 3
On this platform, a Relu has no data members but takes 8 bytes: its vptr. A Scale takes 16: the vptr and its double, where PlainScale needs only the double. twice and half point at the same table.
A call like layer.forward(x) through a reference then takes three steps: read the vptr from the object, read the forward entry from the table it points at, and call that address. GCC’s real tables hold a little more (type information, and a second entry for the destructor), but the idea is the same. The C++ standard doesn’t require vtables at all; it only describes how virtual calls behave. Every major compiler uses them anyway.
PerformanceWhat a virtual call costs
The two extra reads are cheap. The bigger cost is that the compiler usually can’t see which function will run, so it can’t inline it into the caller. When it can prove the dynamic type, for example because the class is final, it can call the function directly. For a tight loop over millions of numbers, call one virtual function per batch, not per number.
Common pitfalls
Object slicing
Pass a derived object to a function that takes the base by value and the function gets a copy of the base part only. The Relu part is sliced off, and the base version runs:
#include <print>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const { return x; }
};
struct Relu : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
};
void run(Layer layer, double x) { // a copy of the Layer part only
std::println("{}", layer.forward(x));
}
int main() {
Relu relu;
run(relu, -2.0);
}Output
-2
The copy is a real Layer, with a vptr to Layer’s table, so virtual can’t help. The fix is to take const Layer&. Making the base abstract helps too: then a Layer can’t be copied by value at all, and this mistake doesn’t compile.
Deleting through a base with no virtual functions
The compiler warning about destructors only fires when the base has virtual functions. Here Read has none, so both compilers stay quiet. But the unique_ptr<Read> deletes a ScoredRead as if it were a Read. That’s undefined behavior; in practice ~ScoredRead never runs, so scores isn’t destroyed, and the memory is freed with the wrong size. AddressSanitizer notices that the block was allocated as one size and freed as another:
#include <memory>
#include <print>
#include <string>
#include <vector>
struct Read {
std::string id;
};
struct ScoredRead : Read {
std::vector<double> scores;
};
int main() {
std::unique_ptr<Read> read = std::make_unique<ScoredRead>();
read->id = "r1";
std::println("{}", read->id);
}This fails when it runs
ERROR: AddressSanitizer: new-delete-type-mismatch on 0x… in thread T0:
object passed to delete has wrong type:
size of the allocated type: 56 bytes;
size of the deallocated type: 32 bytes.
#0 operator delete(void*, unsigned long)
… 2 frames inside the standard library
#3 main main.cpp:18
0x… is located 0 bytes inside of 56-byte region [0x…,0x…)
allocated by thread T0 here:
#0 operator new(unsigned long)
… 1 frame inside the standard library
#2 main main.cpp:15
SUMMARY: AddressSanitizer: new-delete-type-mismatch main.cpp:18 in main
HINT: if you don't care about these errors you may set ASAN_OPTIONS=new_delete_type_mismatch=0The fix depends on what you meant. If Read is meant to be a base, give it virtual ~Read() = default;. If you only wanted ScoredRead to reuse Read’s fields, use composition, as shown above, and own it as std::unique_ptr<ScoredRead>.
Try it yourself
Try it yourself
A ReLU turns every negative number into 0, which here wipes out the signal. Add a LeakyRelu layer that keeps a fraction of negative numbers: slope * x when x isn’t positive. Use it with a slope of 0.25 in place of the Relu.
#include <memory>
#include <print>
#include <string_view>
#include <vector>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const = 0;
virtual std::string_view name() const = 0;
};
struct Relu : Layer {
double forward(double x) const override { return x > 0 ? x : 0.0; }
std::string_view name() const override { return "relu"; }
};
struct Scale : Layer {
double factor;
explicit Scale(double f) : factor{f} {}
double forward(double x) const override { return x * factor; }
std::string_view name() const override { return "scale"; }
};
int main() {
std::vector<std::unique_ptr<Layer>> net;
net.push_back(std::make_unique<Scale>(-3.0));
net.push_back(std::make_unique<Relu>());
net.push_back(std::make_unique<Scale>(0.5));
double x = 2.0;
for (const auto& layer : net) {
x = layer->forward(x);
std::println("after {}: {}", layer->name(), x);
}
}Expected output
after scale: -6 after leaky_relu: -1.5 after scale: -0.75
Show a hint
Copy Relu and give the copy a double slope member set by an explicit constructor. forward returns x when x > 0 and slope * x otherwise; name returns leaky_relu. Then push std::make_unique<LeakyRelu>(0.25) instead of the Relu.
Show a solution
#include <memory>
#include <print>
#include <string_view>
#include <vector>
struct Layer {
virtual ~Layer() = default;
virtual double forward(double x) const = 0;
virtual std::string_view name() const = 0;
};
struct LeakyRelu : Layer {
double slope;
explicit LeakyRelu(double s) : slope{s} {}
double forward(double x) const override { return x > 0 ? x : slope * x; }
std::string_view name() const override { return "leaky_relu"; }
};
struct Scale : Layer {
double factor;
explicit Scale(double f) : factor{f} {}
double forward(double x) const override { return x * factor; }
std::string_view name() const override { return "scale"; }
};
int main() {
std::vector<std::unique_ptr<Layer>> net;
net.push_back(std::make_unique<Scale>(-3.0));
net.push_back(std::make_unique<LeakyRelu>(0.25));
net.push_back(std::make_unique<Scale>(0.5));
double x = 2.0;
for (const auto& layer : net) {
x = layer->forward(x);
std::println("after {}: {}", layer->name(), x);
}
}LeakyRelu overrides both pure virtual functions, so it isn't abstract and can be created. The loop in main calls forward and name through unique_ptr<Layer>, and the vtable sends each call to LeakyRelu's version without any change to the loop.
Saved in this browser only.