Dynamic vs. Static Polymorphism

Learn about polymorphism and to distinguish between dynamic and static types of polymorphism.

When we learn about object-oriented programming, we learn about its fundamental principles, which are abstraction, encapsulation, inheritance, and polymorphism. C++ is a multi-paradigm programming language that supports object-oriented programming too. Although a broader discussion on the principles of object-oriented programming is beyond the scope of this section and this course, it’s worth discussing at least some aspects related to polymorphism.

Polymorphism

So, what is polymorphism? The term is derived from the Greek words for “many forms.” In programming, it’s the ability of objects of different types to be treated as if they were of the same type. The C++ standard actually defines a polymorphic class as follows: “A class that declares or inherits a virtual function is called a polymorphic class.”

It also defines polymorphic objects based on this definition, as follows: “Some objects are polymorphic; the implementation generates information associated with each such object that makes it possible to determine that object’s type during program execution.”

However, this actually refers to what is called dynamic polymorphism (or late binding), but there is yet another form of polymorphism called static polymorphism (or early binding). Dynamic polymorphism occurs at runtime with the help of interfaces and virtual functions, while static polymorphism occurs at compile-time with the help of overloaded functions and templates. This is described in Bjarne Stroustrup’s glossary of terms for the C++ language:

Polymorphism - providing a single interface to entities of different types. virtual functions provide dynamic (run-time) polymorphism through an interface provided by a base class. Overloaded functions and templates provide static (compile-time) polymorphism.

Example of dynamic polymorphism

Let’s look at an example of dynamic polymorphism. The following is a hierarchy of classes representing different units in a game. These units may attack others, so there’s a base class with a pure virtual function called attack. There are also several derived classes implementing specific units that override this virtual function doing different things (of course, for simplicity, here we just print a message to the console). It looks as follows:

Get hands-on with 1200+ tech skills courses.