Polymorphism is the property that different types support the same interface. In C++, we distinguish between dynamic polymorphism and static polymorphism.
Now we are done with the basics, details, and techniques around templates, let me write about the design with templates. There are many types of polymorphism, but I want to concentrate on one aspect. Does the polymorphism dispatch happen at run time or at compile time? Run-time polymorphism is based on object orientation and virtual functions in C++, and compile-time polymorphism is based on templates.
Both polymorphisms have pros and cons that I discuss in the following post.
Here are the key facts. Dynamic Polymorphism takes place at run time, is based on object orientation, and enables us to separate between the interface and the implementation of a class hierarchy. To get late binding, dynamic dispatch, or dispatch at run time, you need virtuality and an indirection such as a pointer or a reference.
writeMessageReference (line 1) or
writeMessagePointer (line 2) require a reference or a pointer to an object of type
MessageSeverity. Classes publicly derived from
MessageSeverity such as
MessageFatal support the so-called Liskov substitution principle. This means that a
MessageWarning, or a
MessageFatal is a
Here is the output of the program.
You may ask yourself why the member function
writeMessage of the derived class and not the base class is called. Here, late binding kicks in. The following explanation applies to lines (3) to (8). For simplicity, I only write about the line (6):
MessageSeverity* messPoin1 = new MessageInformation. messPoint1 has essentially two types. A static type
MessageSeverity and a dynamic type
MessageInformation. The static type
MessageSeverity stands for its interface, and the dynamic type
MessageInformation for its implementation. The static type is used at compile time, and the dynamic type at run time. At run time, messPoint1 is of type
MessageInformation; therefore, the virtual function
MessageInformation is called. Once more, dynamic dispatch requires an indirection such as a pointer or reference and virtuality.
I regard this kind of polymorphism as a contract-driven design. A function such as
writeMessagePointer requires that each object has to support that it is publicly derived from
MessageSeverity. If this contract is not fulfilled, the compiler complains.
In contrast to contract-driven design, we also have a behavioral-driven design with static polymorphism.
Let me start with a short detour.
In Python, you care about behavior and not about formal interfaces. This idea is well-known as duck typing. To make it short, the expression goes back to the poem from James Whitcomb Rileys: Here it is:
“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
What does that mean? Imagine a function
acceptOnlyDucks that only accepts ducks as an argument. In statically typed languages such as C++, all types which are derived from
Duck can be used to invoke the function. In Python, all types, which behave like
Duck‘s, can be used to invoke the function. To make it more concrete. If a bird behaves like a
Duck, it is a
Duck. Python often uses a proverb to describe this behavior quite well.
Don’t ask for permission; ask for forgiveness.
In our Duck’s case, you invoke the function
acceptsOnlyDucks with a bird and hope for the best. If something terrible happens, you catch the exception with an except clause. Typically, this strategy works very well and very fast in Python.
Okay, this is the end of my detour. Maybe you wonder why I wrote about duck typing in this C++ post. The reason is relatively straightforward. Thanks to templates, we have duck typing in C++.
This means that you can refactor the previous program
dispatchStaticPolymorphism.cpp using duck typing.
The function template
writeMessage (line 1) applies duck typing.
writeMessage assumes that all objects messServer support the member function
writeMessage. If not, the compilation would fail. The main difference to Python is that the error happens in C++ at compile time, but in Python at run time. Finally, here is the output of the program.
writeMessage behaves polymorphic but is neither type-safe nor writes a readable error message in case of an error. At least I can quickly fix the last issue with concepts in C++20. You can read more about concepts in my previous posts about concepts. In the following example, I define and use the concept
MessageServer (line 1).
The concept MessageServer (line 1) requires that an object
t of type
T has to support the call
t.writeMessage. Line (2) applies the concept in the function template
So far, I have only written about the polymorphic behavior of templates but not static polymorphism. This changes in my next post. I present the so-called CRTP idiom. CRTP stands for the Curiously Recurring Template Pattern and means a technique in C++ in which you inherit a class
Derived from a template class
Derived as a template parameter:
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, 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, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
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++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,