Polymorphism Examples

Learn about the types of polymorphism with coding examples.

Static polymorphism example

In the coding playground below, we have taken an example of logging messages to the console. We’ve created a type hierarchy with a templatized (generic) struct named MessageSeverity (lines 13–21) defined as the base. There are three subtypes:

  • MessageInformation on lines 23–27
  • MessageWarning on lines 29–33
  • MessageFatal on line 35

The base structure defines a member function, writeMessage(), which calls the writeMessageImplementation() function of the actual subtype (line 16). This structure also defines a default implementation of writeMessageImplementation. The MessageFatal class utilizes this default implementation by means of inheritance, whereas the other two subtypes override this function.

In main(), we create instances of each type of struct and call the writeMessage() function. The compiler binds the calls on lines 50 and 53 to the overridden functions, whereas the call on line 56 is bound to the base implementation.

Get hands-on with 1200+ tech skills courses.