Polymorphism is composed of two words: poly denotes more than one, and morphs indicate forms. Thus, polymorphism refers to the ability to take more than one form. This trait causes the same elements, such as functions and operators, to behave differently in different contexts.
In C++, polymorphism is classified into two types. They are:
During the compilation stage, the compiler determines which functions to perform during program execution. At compilation time, it matches the number and type of parameters to overloaded functions or operators. In C++, the compiler uses compile-time polymorphism in two ways:
This allows numerous functions with the same name to coexist, distinguished by parameter types and/or number of parameters, allowing the same function name to handle a variety of data types and operations.
This enables custom definitions for the behavior of operators (such as +, -, *, and so on) when used with user-defined data types, allowing for the intuitive use of operators with objects.
In this case, the compiler does not know which functions to perform during program execution. The function call is resolved at runtime based on the object type, rather than during compilation. It signifies that the function is called by either the parent class object or the derived class object. This is also known as dynamic or late binding. C++ supports runtime polymorphism in two ways:
Function overriding in C++ enables a derived class to offer a particular implementation of a function that is already defined in its base class. This allows the derived class to override the behavior of the base class function.
In C++, virtual functions are member functions declared with the virtual keyword in a base class that can be overridden by derived classes. They enable dynamic binding, which allows the appropriate function to be invoked based on the actual object type at runtime.