Polymorphism and Dynamic Binding
Published by
sanya sanya
Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common base class. It enables you to use a single interface to represent multiple types.
Polymorphism is achieved through function overriding and is categorized into two types: compile-time polymorphism and runtime polymorphism.
1. Compile-time Polymorphism:
- Also known as static polymorphism.
- Achieved using function overloading and operator overloading.
- Function overloading allows multiple functions with the same name but different parameter lists to coexist in a class. The appropriate function is selected based on the number or type of arguments during compile-time.
Example:
class MathOperations {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
int main() {
MathOperations math;
int result1 = math.add(2, 3); // Output: 5
double result2 = math.add(2.5, 3.7); // Output: 6.2
return 0;
}
2. Runtime Polymorphism:
- Also known as dynamic polymorphism.
- Achieved using virtual functions and dynamic binding.
- Virtual functions are functions declared in the base class with the ‘virtual’ keyword and can be overridden in derived classes.
- When a virtual function is called through a base class pointer or reference, the actual function that gets executed is determined at runtime based on the type of the object being pointed to or referred to. This is known as dynamic binding.
Example:
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape* shapePtr;
Circle circle;
Square square;
shapePtr = &circle;
shapePtr->draw(); // Output: Drawing a circle
shapePtr = □
shapePtr->draw(); // Output: Drawing a square
return 0;
}
In this example, we have a base class ‘Shape’ with a virtual function ‘draw()’. The derived classes ‘Circle’ and ‘Square’ override the ‘draw()’ function with their own specific implementations. When we call the ‘draw()’ function using the ‘shapePtr’, the correct version of the function is executed based on the actual type of the object pointed to, demonstrating dynamic binding and runtime polymorphism.
Library
WEB DEVELOPMENT
FAANG QUESTIONS