C++ Polymorphism
Polymorphism is a core concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. It enables the same code to be written in a generic way, capable of working with objects of different types, without the need for explicit type checking.
There are two main types of polymorphism in C++: compile-time (static) polymorphism and run-time (dynamic) polymorphism.
1. Compile-Time (Static) Polymorphism:
Compile-time polymorphism is achieved through function overloading and template specialization.
Function Overloading: Function overloading allows multiple functions with the same name but different parameter lists to exist. The appropriate function to be called is determined at compile-time based on the number, types, and order of arguments.
void print(int num) {
cout << "Printing an integer: " << num << endl;
}
void print(double num) {
cout << "Printing a double: " << num << endl;
}
int main() {
print(10); // Calls the int version of print()
print(3.14); // Calls the double version of print()
return 0;
}
Template Specialization: Templates allow you to write generic code that can be customized for different data types. Template specialization allows you to provide specific implementations for certain data types.
template <typename T>
void print(T value) {
cout << "Printing a value: " << value << endl;
}
template <>>
void print(string value) {
cout << "Printing a string: " << value << endl;
}
int main() {
print(10); // Calls the generic print() function
print(3.14); // Calls the generic print() function
print("Hello, world!"); // Calls the specialized print() function for strings
return 0;
}
2. Run-Time (Dynamic) Polymorphism:
Run-time polymorphism is achieved through inheritance and virtual functions. It allows you to call the appropriate member function based on the actual type of the object, determined at runtime.
Inheritance and Virtual Functions: A base class can declare a virtual function that can be overridden by derived classes. When a virtual function is called through a pointer or reference to a base class, the derived class's implementation is executed.
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* shape1 = new Circle();
Shape* shape2 = new Square();
shape1->draw(); // Calls the draw() function of Circle
shape2->draw(); // Calls the draw() function of Square
delete shape1;
delete shape2;
return 0;
}
Polymorphism allows you to write more flexible and extensible code, as it enables the use of common interfaces and behavior across different types of objects. It promotes code reuse, abstraction, and modularity in object-oriented programming.