Polymorphism in C++
Introduction
Polymorphism means "many forms". It allows a single interface (function/operator) to behave differently based on the type of data or object it operates on.
Two broad categories: compile-time (static binding) and run-time (dynamic binding via virtual functions).
Classification Diagram
Fig 3.3 β Polymorphism splits into compile-time and run-time techniques.
Definition
Compile-Time Polymorphism
Achieved through function overloading and operator overloading. Resolved by the compiler.
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
// compiler picks based on argument typesRun-Time Polymorphism
Achieved through virtual functions and function overriding. Resolved at runtime via vtable.
class Base { public: virtual void show(){ cout<<"Base\n"; } };
class Derived : public Base { public: void show(){ cout<<"Derived\n"; } };
int main(){ Base* p=new Derived(); p->show(); /* Derived */ }UML View
Fig 3.4 β Derived overrides virtual show() of Base.
Important Questions
Short Questions
- Define polymorphism.
- Difference between compile-time and run-time polymorphism?
- What is function overloading?
- What is a virtual function?
Long Questions
- Explain run-time polymorphism with a C++ example.
- Compare static and dynamic binding.
MCQ Practice
1. Which of these gives run-time polymorphism?
- Function overloading
- Virtual functions
- Operator overloading
- Templates
2. Compile-time polymorphism is also called:
- Static binding
- Dynamic binding
- Late binding
- Runtime binding
3. Virtual functions are resolved at:
- Compile time
- Run time
- Link time
- Never
4. Function overloading is based on:
- Return type only
- Number/type of parameters
- Function name
- Access specifier
5. Which keyword enables run-time polymorphism?
- override
- virtual
- static
- inline
Quick Revision
- Polymorphism = many forms.
- Compile-time: overloading (static binding).
- Run-time: virtual functions/overriding (dynamic binding).
- Virtual uses vtable for dispatch.