virtual keyword in the base class.Virtual functions enable polymorphism, allowing derived classes to override base class functions, with the correct function called at runtime based on the object’s type (dynamic binding). Key subtopics include:
override specifier (C++11 and later):While not strictly required, using the override keyword when redefining a virtual function in a derived class is good practice. It explicitly indicates that the function is intended to override a base class virtual function and helps the compiler catch potential errors (e.g., mismatched signatures).
class Base{
public:
virtual return_type functionName(){
// Function body
}
};
class Derived : public Base{
public:
// Overriden virtual function of the base class
return_type fnctionName(){
// Function body
}
}
The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is called polymorphism.
In C++, polymorphism concept can be applied to functions and operators. A single function can work differently in different situations. Similarly, an operator works different when used in different context.
Types of Polymorphism
Polymorphism in C++ can be classified into two types: