Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to Polymorphism

Introduction to PolymorphismIntroduction to Polymorphism

Constructor

Polymorphism stands as a pivotal concept. It is derived from Greek words meaning "many shapes" and it allows objects of different classes to be treated as object of a common superclass. The most significant aspect is the ability of different entities to respond in their own way to the same message or method call.

Types of Polymorphism

There are two main types of polymorphism: compile-time (static) and runtime (dynamic). Understanding the nuances and applications of each type of polymorphism is crucial for writing robust and adaptable code.

  • Compile-Time Polymorphism: This is achieved using function overloading and operator overloading, where the function to be executed is determined during compilation.
  • Runtime Polymorphism: This is mainly achieved through the use of virtual functions, enabling a function to be overridden in derived classes and its behavior to be determined at runtime.

Note

In this course, we will dive deeply into runtime polymorphism, as it represents one of the fundamental paradigms of object-oriented programming. Additionally, we will touch upon compile-time polymorphism within the context of classes.


Application and need for polymorphism

An excellent way to understand polymorphism is through a real-world analogy. Consider a graphic user interface with a button. This button can be used in different contexts: as a upload button, a reset button, or a cancel button.

upload button
circular button
cancel button

Each button executes a distinct action upon being clicked, but all of them are essentially serve as buttons. Look the theoretical implementation of this concept.

h

UploadButton.h

h

ResetButton.h

h

CancelButton.h

Considering that all buttons share the same onClick() method with varying implementations, let's dive deeper. What if we require a function that accepts an object belonging to one of the button classes as a parameter?

cpp

main.cpp

As you can see manually creating separate functions for each button can create complexity, especially during modifications, as each function must be edited individually if issues arise. Also, in the main function, additional checks will be necessary to determine which function to call.

If only there were an easy way to fix these issues... Fortunately, there is! Polymorphism allows for easy resolution of these problems.


1. What is the literal meaning of the term polymorphism?
2. Which type of polymorphism is determined during runtime?

question-icon

What is the literal meaning of the term polymorphism?

Select the correct answer

question-icon

Which type of polymorphism is determined during runtime?

Select the correct answer

Everything was clear?

Section 5. Chapter 1
some-alt