Compile-time Polymorphism in C++
Introduction
Polymorphism is a core concept in Object-Oriented Programming (OOP) that allows objects or functions to take on multiple forms. In C++, polymorphism can be categorized into two types: Compile-time (or static) polymorphism and Run-time (or dynamic) polymorphism. This tutorial focuses on Compile-time Polymorphism.
What is Compile-time Polymorphism?
Compile-time polymorphism is achieved through function overloading and operator overloading. It is called compile-time because the decision of which function or operator to invoke is made at compile time.
Function Overloading
Function overloading allows you to define multiple functions with the same name but different parameters. The appropriate function is selected based on the number and type of arguments passed.
Example:
C++ Code:
#include <iostream> using namespace std; // Overloaded functions void print(int i) { cout << "Integer: " << i << endl; } void print(double f) { cout << "Float: " << f << endl; } void print(const char* c) { cout << "String: " << c << endl; } int main() { print(10); // Calls print(int) print(10.5); // Calls print(double) print("Hello"); // Calls print(const char*) return 0; }
Output:
Float: 10.5
String: Hello
Operator Overloading
Operator overloading allows you to redefine the way operators work for user-defined types (e.g., classes). This enables the use of operators like +, -, *, etc., with objects of those types.
Example:
C++ Code:
#include <iostream> using namespace std; class Complex { public: float real; float imag; Complex() : real(0), imag(0) {} Complex(float r, float i) : real(r), imag(i) {} // Operator overloading Complex operator + (const Complex& obj) { Complex temp; temp.real = real + obj.real; temp.imag = imag + obj.imag; return temp; } void display() { cout << real << " + " << imag << "i" << endl; } }; int main() { Complex c1(3.4, 5.5); Complex c2(1.2, 2.3); Complex c3; c3 = c1 + c2; // Calls overloaded operator+ c3.display(); // Displays the result return 0; }
Output:
Advantages of Compile-time Polymorphism
Compile-time polymorphism offers several advantages:
- Efficiency: Since the decision is made at compile time, it can result in more efficient code.
- Readability: Overloading functions and operators can make the code more readable and intuitive.
- Maintainability: It allows for the same function name to be used for different purposes, making the code easier to maintain.
Conclusion
Compile-time polymorphism is a powerful feature in C++ that enhances the flexibility and readability of the code. By using function overloading and operator overloading, developers can write more intuitive and maintainable code. Understanding and utilizing compile-time polymorphism is essential for mastering C++ and creating efficient applications.