Understanding Polymorphism in C++
Understanding Polymorphism in C++
Dynamic Behavior
Methods execute based on the object's runtime type.
Different Parameters
Functions differ by parameter type or count.
Compile-Time Resolution
Decided by the compiler before runtime.
Example
int add(int,int);
float add(float,float);
Compile-Time
Polymorphism:
Templates
Generic Code
Functions and classes adapt to any data type.
Code Generation
Real code created for each type at compile-time.
Example
template <typename T> T max(T a, T b);
PROGRAM:
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
virtual void draw() {
cout << "Drawing a generic shape." << endl;
}
};
// Derived class 1
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle using compass." << endl;
}
};
// Derived class 2
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a Rectangle using ruler." << endl;
}
};
// Derived class 3
class Triangle : public Shape {
public:
void draw() override {
cout << "Drawing a Triangle using scale." << endl;
}
};
int main() {
Shape* s;
Circle c;
Rectangle r;
Triangle t;
s = &c;
s->draw();
s = &r;
s->draw();
s = &t;
s->draw();
return 0;
}
OUTPUT:
Run-Time
Polymorphism: Virtual
Functions
1 Inheritance
Derived classes inherit from base class.
2 Virtual Functions
Declared in base, overridden in derived classes.
3 Dynamic Dispatch
Function call resolved at runtime based on object type.
4 Example
<virtual void draw();>
Conclusion:
Polymorphism Powers
OOP
Critical for Robust Design
Enables flexible, reusable, maintainable code.
Supports Scalability
Fundamental in modern software development.