Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to Polymorphism | Polymorphism Overview
C++ OOP
course content

Зміст курсу

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

book
Introduction to Polymorphism

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.

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

ResetButton

h

CancelButton

copy
1234
class UploadButton : public Button { public: void onClick() { std::cout << "Upload" << std::endl; } };

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

copy
1234567891011
void user_clicked_upload_button(const UploadButton& btn) { btn.onClick(); } void user_clicked_reset_button(const ResetButton& btn) { btn.onClick(); } void user_clicked_cancel_button(const CancelButton& btn) { btn.onClick(); }

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. Polymorphism allows for easy resolution of these problems.

What is the literal meaning of the term polymorphism?

What is the literal meaning of the term polymorphism?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 1
We're sorry to hear that something went wrong. What happened?
some-alt