C++ Overloading
C++ Overloading refers to the ability to define multiple functions or operators with the same name but different parameter lists or different behavior. It allows you to create functions or operators that can perform different actions based on the types and/or number of arguments provided.
There are two types of overloading in C++: function overloading and operator over
Function Overloading
Function overloading allows you to define multiple functions with the same name but different parameter lists. The compiler selects the appropriate function to call based on the arguments provided.
// Function Overloading Example
void print(int num) {
cout << "Printing an integer: " << num << endl;
}
void print(double num) {
cout << "Printing a double: " << num << endl;
}
void print(string str) {
cout << "Printing a string: " << str << endl;
}
int main() {
print(10); // Calls print(int)
print(3.14); // Calls print(double)
print("Hello, World!"); // Calls print(string)
return 0;
}
In the example above, three different print functions are defined. The appropriate function is selected based on the type of argument passed when calling the function.
Operator Overloading
Operator overloading allows you to redefine the behavior of operators for user-defined types. It enables you to use operators such as +, -, *, /, ==, <<, etc., with custom-defined classes or structures.
// Operator Overloading Example
class Vector {
private:
int x, y;
public:
Vector(int xVal, int yVal) : x(xVal), y(yVal) {}
Vector operator+(const Vector& other) {
return Vector(x + other.x, y + other.y);
}
void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Vector v1(2, 3);
Vector v2(4, 5);
Vector sum = v1 + v2; // Calls the overloaded + operator
sum.display(); // Output: (6, 8)
return 0;
}
In the example above, the + operator is overloaded for the Vector class. The operator allows adding two Vector objects together, resulting in a new Vector object with the summed values of the individual components.
Overloading functions and operators can make code more readable, intuitive, and convenient. It allows you to provide different behaviors for functions or operators based on the context in which they are used, reducing the need for creating multiple functions or operators with different names.