Course Content
C++ OOP
C++ OOP
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.
UploadButton
ResetButton
CancelButton
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?
main
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.
Thanks for your feedback!