Dynamic and Static Polymorphism

Dynamic and Static Polymorphism

This post is a cross-post from www.ModernesCpp.com.

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++, 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, it 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 two ingredients: 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.

No alt text provided for this image

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 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 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.

No alt text provided for this image


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. There is often a proverb used in Python to describe this behavior quite well.

Don't ask for permission, ask for forgiveness.

In the case of our Duck, this means, that you invoke the function acceptsOnlyDucks with a bird and hope for the best. If something bad 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 quite straightforward. Thanks to templates, we have duck typing in C++.

This means, that you can refactor the previous program disptachStaticPolymorphism.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.

No alt text provided for this image


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 easily 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, Marko, G Prvulovic, Reinhold Dr?ge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschl?ger, Red Trip, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Haken Gedek, Bernd Mühlhaus, Challanger, Matthieu Bolt, Stephen Kelley, Kyle Dean, and Tusar Palauri, and Dmitry Farberov.

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, and Mipko.

My special thanks to Embarcadero

?My special thanks to PVS-Studio

?

Mentoring Program

My new mentoring program "Fundamentals for C++ Professionals" starts in April. Get more information here: https://bit.ly/MentoringProgramModernesCpp.

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.

New

Contact Me

Modernes C++



要查看或添加评论,请登录

Rainer Grimm的更多文章

社区洞察

其他会员也浏览了