Let's talk in this post about rules for class hierarchies in general and in particular. The C++ core guidelines have about thirty rules in total; therefore, I have a lot to talk about.
At first, what is a class hierarchy? The C++ core guidelines give a clear answer. Let me rephrase it. A class hierarchy represents a set of hierarchically organized concepts. Base classes act typically as interfaces. They are two uses for interfaces. One is called implementation inheritance and the other interface inheritance.
The first three lines are more general or to say it differently: they are a summary of the more detailed rules.

Class hierarchy rule summary:
This is quite obvious. If you model something in the code which has an inherently hierarchical structure you should use a hierarchy. For me, the easiest way to reason about my code is if I have a natural match between the code and the world.
For example, I had to model a complex system. This system was a family of defibrillators that consist of a lot of subsystems. For example, one subsystem was the user interface. The requirement was that the defibrillators should use different user interfaces such as a keyboard, a touch screen, or a few buttons. This system of subsystem was inherently hierarchical; therefore, I modeled it a hierarchical way. The great benefit was that the software was quite easy to explain in a top-down fashion because there was this natural match between the real hardware and the software.
But of course, the classic example for using a hierarchy in the design of a graphical user interface (GUI). This is the example the C++ core guidelines are using.
class DrawableUIElement {
public:
virtual void render() const = 0;
// ...
};
class AbstractButton : public DrawableUIElement {
public:
virtual void onClick() = 0;
// ...
};
class PushButton : public AbstractButton {
virtual void render() const override;
virtual void onClick() override;
// ...
};
class Checkbox : public AbstractButton {
// ...
};
If something is not inherently hierarchical, you should not model it in a hierarchical way. Have a look here.
template<typename T>
class Container {
public:
// list operations:
virtual T& get() = 0;
virtual void put(T&) = 0;
virtual void insert(Position) = 0;
// ...
// vector operations:
virtual T& operator[](int) = 0;
virtual void sort() = 0;
// ...
// tree operations:
virtual void balance() = 0;
// ...
};
Why is the example bad? You have only to read the comments. The class template Container consists of pure virtual functions for modeling a list, a vector, and a tree. That means if you use Container as an interface you have to implement three disjunct concepts.
An abstract class is a class that has at least one pure virtual function. A pure virtual function (virtual void function() = 0 ) is a function that must be implemented by a derived class if that class should not be abstract.
Only for completeness reasons. An abstract class can provide implementations of pure virtual functions. A derived class can, therefore, use these implementations.
Interfaces should usually consist of public pure virtual functions and a default/empty virtual destructor (virtual ~My_interface() = default). If you don't follow the rule, something bad may happen.
class Goof {
public:
// ...only pure virtual functions here ...
// no virtual destructor
};
class Derived : public Goof {
string s;
// ...
};
void use()
{
unique_ptr<Goof> p {new Derived{"here we go"}};
f(p.get()); // use Derived through the Goof interface
} // leak
If p goes out of scope, it will be destroyed. But Goof has no virtual destructor; therefore, the destructor of Goof and not Derived is called. The bad effect is that destructor of the string s is not called.
Abstract classes are about the separation of interface and implementation. The effect is that you can use a different implementation of Device in the following example during runtime because you only depend on the interface.
struct Device {
virtual void write(span<const char> outbuf) = 0;
virtual void read(span<char> inbuf) = 0;
};
class D1 : public Device {
// ... data ...
void write(span<const char> outbuf) override;
void read(span<char> inbuf) override;
};
class D2 : public Device {
// ... different data ...
void write(span<const char> outbuf) override;
void read(span<char> inbuf) override;
};
In my seminars to design patterns, I often call this rule the meta-design pattern that is the base for a lot of the design patterns from the most influential software book: Design Patterns: Elements of Reusable Object-Oriented Software.
Designing rules for classes in a hierarchy summary:
Here are the more detailed rules in summary. The guidelines have 15 of them.
Today I write about the first three.
An abstract class has typically no data and, therefore, needs no constructor to initialize them.
A class with a virtual function is most of the time used via a pointer or a reference to the base. If you explicitly delete the derived class via a pointer or a reference to the base or indirectly via a smart pointer, you want to be sure, that also the destructor of the derived class is called. This rule is quite similar to rule C.121 which talks about pure virtual functions.
Another way to solve the destruction issue is to have a protected and non-virtual base class destructor. This destructor guarantees that you can not delete a derived object via a pointer or reference to the base.
In C++11 we have three keywords to deal with overriding.
- virtual: declares a function that can be overwritten in derived classes
- override: ensures that the function is virtual and overwrites a virtual function of a base class
- final: ensures that the function is virtual and cannot be overridden by a derived class
According to the guidelines, the rules for the usage of the three keywords are straightforward: "Use virtual
only when declaring a new virtual function. Use override
only when declaring an overrider. Use final
only when declaring a final overrider."
struct Base{
virtual void testGood(){}
virtual void testBad(){}
};
struct Derived: Base{
void testGood() final {}
virtual void testBad() final override {}
};
int main(){
Derived d;
}
The method testBad() in the class Derived has a lot of redundant information.
- You should only use final or override, if the function is virtual. Skip virtual: void testBad() final override{}
- Using the keyword final without the virtual keyword is only valid if the function is already virtual; therefore, the function must override a virtual function of a base class. Skip override: void testBad() final {}
What's next?
The remaining twelve rules for class hierarchies are missing. My next post will close this gap.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Dominik Vošček, and Rob North.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.
My special thanks to Embarcadero 
My special thanks to PVS-Studio 
My special thanks to Tipi.build 
Seminars
I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable (Online)
German
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ - The Core Language
- C++ - The Standard Library
- C++ - Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
New
- Clean Code with Modern C++
- C++20
Contact Me
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: This email address is being protected from spambots. You need JavaScript enabled to view it.
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++,

Comments
I guess I'll just sum it up what I wrote and say, I'm thoroughly
enjoying your blog. I too am an aspiring blog blogger but I'm still
new to the whole thing. Do you have any recommendations for beginner blog writers?
I'd genuinely appreciate it.
RSS feed for comments to this post