1. What is Polymorphism?
Polymorphism = “Many Forms”
It allows the same function or operator to behave differently in different
situations.
Definition:
Polymorphism is an OOP feature that allows one interface to be used for multiple
purposes.
Example idea:
A person acts as:
student in class
customer in shop
friend at home
Same person → different behavior.
2. Types of Polymorphism
Polymorphism in C++ is of two types:
A) Compile-Time Polymorphism (Early Binding / Static Binding)
Occurs at compile time.
1 Function Overloading
1️⃣
Same function name, different parameters.
Example:
int add(int a, int b);
float add(float x, float y);
add() works differently depending on parameter type/count.
2️⃣ Operator Overloading
Redefining the meaning of an operator.
Example:
Complex operator + (Complex c);
+ performs addition of two Complex objects.
✔ Advantages of Compile-Time Polymorphism
faster execution
clear readability
easy to use
B) Run-Time Polymorphism (Late Binding / Dynamic Binding)
Occurs at runtime.
1️⃣ Function Overriding
Same function name and signature in:
base class
derived class
Used with inheritance.
Example:
class A {
public:
virtual void show() {
cout << "Base class";
}
};
class B : public A {
public:
void show() {
cout << "Derived class";
}
};
How it works?
Base class pointer → Derived class object
Calls derived class function at runtime
2️⃣ Virtual Functions
Declared in base class using virtual keyword
Enable runtime polymorphism
Rules:
Must be in base class
Cannot be static
Accessed through pointers
✔ Advantages of Run-Time Polymorphism
flexibility
extensibility
allows overriding base class behavior
3. Difference Between Compile-Time & Run-Time Polymorphism
Feature Compile-Time Run-Time
Binding Early (static) Late (dynamic)
Mechanism Overloading Overriding
Speed Fast Slightly slow
Keyword No keyword needed Uses virtual
Executed Compile time Run time
4. Why Polymorphism is Important?
Provides flexibility
Helps in code reusability
Allows same interface for different actions
Makes program easier to maintain
5. Short Exam Answers (Quick Revision)
Q: Define Polymorphism.
Polymorphism is the ability of an object to take many forms. It allows the same
function or operator to behave differently based on context.
Q: What is function overloading?
Using the same function name with different parameters.
Q: What is function overriding?
Redefining a base class function in a derived class.
Q: What are virtual functions?
Functions declared with the virtual keyword to enable runtime polymorphism.