Dynamic and Static Polymorphism
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.
Dynamic Polymorphism
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.
// dispatchDynamicPolymorphism.cpp #include <chrono> #include <iostream> auto start = std::chrono::steady_clock::now(); void writeElapsedTime(){ auto now = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = now - start; std::cerr << diff.count() << " sec. elapsed: "; } struct MessageSeverity{ virtual void writeMessage() const { std::cerr << "unexpected" << '\n'; } }; struct MessageInformation: MessageSeverity{ void writeMessage() const override { std::cerr << "information" << '\n'; } }; struct MessageWarning: MessageSeverity{ void writeMessage() const override { std::cerr << "warning" << '\n'; } }; struct MessageFatal: MessageSeverity{}; void writeMessageReference(const MessageSeverity& messServer){ // (1) writeElapsedTime(); messServer.writeMessage(); } void writeMessagePointer(const MessageSeverity* messServer){ // (2) writeElapsedTime(); messServer->writeMessage(); } int main(){ std::cout << '\n'; MessageInformation messInfo; MessageWarning messWarn; MessageFatal messFatal; MessageSeverity& messRef1 = messInfo; // (3) MessageSeverity& messRef2 = messWarn; // (4) MessageSeverity& messRef3 = messFatal; // (5) writeMessageReference(messRef1); writeMessageReference(messRef2); writeMessageReference(messRef3); std::cerr << '\n'; MessageSeverity* messPoin1 = new MessageInformation; // (6) MessageSeverity* messPoin2 = new MessageWarning; // (7) MessageSeverity* messPoin3 = new MessageFatal; // (8) writeMessagePointer(messPoin1); writeMessagePointer(messPoin2); writeMessagePointer(messPoin3); std::cout << '\n'; }
The function 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 MessageInformation
, MessageWarning
, or MessageFatal
support the so-called Liskov substitution principle. This means that a MessageInformation
, MessageWarning
, or a MessageFatal
is a MessageSeverity
.
Here is the output of the program.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
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 writeMessage
of 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.
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.
// duckTyping.cpp #include <chrono> #include <iostream> auto start = std::chrono::steady_clock::now(); void writeElapsedTime(){ auto now = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = now - start; std::cerr << diff.count() << " sec. elapsed: "; } struct MessageSeverity{ void writeMessage() const { std::cerr << "unexpected" << '\n'; } }; struct MessageInformation { void writeMessage() const { std::cerr << "information" << '\n'; } }; struct MessageWarning { void writeMessage() const { std::cerr << "warning" << '\n'; } }; struct MessageFatal: MessageSeverity{}; template <typename T> void writeMessage(T& messServer){ // (1) writeElapsedTime(); messServer.writeMessage(); } int main(){ std::cout << '\n'; MessageInformation messInfo; writeMessage(messInfo); MessageWarning messWarn; writeMessage(messWarn); MessageFatal messFatal; writeMessage(messFatal); std::cout << '\n'; }
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.
The function 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).
// duckTypingWithConcept.cpp #include <chrono> #include <iostream> template <typename T> // (1) concept MessageServer = requires(T t) { t.writeMessage(); }; auto start = std::chrono::steady_clock::now(); void writeElapsedTime(){ auto now = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = now - start; std::cerr << diff.count() << " sec. elapsed: "; } struct MessageSeverity{ void writeMessage() const { std::cerr << "unexpected" << '\n'; } }; struct MessageInformation { void writeMessage() const { std::cerr << "information" << '\n'; } }; struct MessageWarning { void writeMessage() const { std::cerr << "warning" << '\n'; } }; struct MessageFatal: MessageSeverity{}; template <MessageServer T> // (2) void writeMessage(T& messServer){ writeElapsedTime(); messServer.writeMessage(); } int main(){ std::cout << '\n'; MessageInformation messInfo; writeMessage(messInfo); MessageWarning messWarn; writeMessage(messWarn); MessageFatal messFatal; writeMessage(messFatal); std::cout << '\n'; }
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 writeMessage
.
What’s next?
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 Base
and Base
has Derived
as a template parameter:
template <typename T> class Base { ... }; class Derived : public Base<Derived> { ... };
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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
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 | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Thanks for the explanation! I think there’s a typo in this line
> This means that you can refactor the previous program disptachStaticPolymorphism.cpp using duck typing.
it should be dispatchDynamicPolymorphism.cpp
Fixed, and thanks a lot,
Rainer
Thanks a lot for the very useful posting.
Might I ask if I could copy over your last code example (duckTypingWithConcept.cpp) for my own blog in a different language?
Sure, if you mention my blog as the source of the example.