Course Content
C++ OOP
C++ OOP
Introduction to Polymorphism
Polymorphism stands as a pivotal concept. Derived from Greek meaning "many shapes," it allows objects of different classes
to be treated as an 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 how and when to use each is crucial for writing flexible, efficient code.
Compile-time polymorphism: occurs through function or operator overloading, where the method to execute is determined at compile time.
Runtime polymorphism: uses virtual functions, allowing derived classes to override base class methods, with the correct method chosen at runtime.
Application and need for polymorphism
An excellent way to understand polymorphism is through a real-world analogy. Consider a graphical user interface with a button. This button can behave differently depending on the contextβit might function as an 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.h
ResetButton.h
CancelButton.h
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 need a function that accepts an object belonging to one of the button classes
as a parameter?
main.cpp
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!