In C++, function overloading and operator overloading are powerful features that allow developers to create multiple functions or operators with the same name but different implementations. This enhances code readability and usability.
Function overloading allows you to define multiple functions with the same name but different parameter types or counts. The correct function is chosen based on the arguments passed during the function call.
#include
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Function to add two double values
double add(double a, double b) {
return a + b;
}
int main() {
std::cout << "Add two integers: " << add(2, 3) << std::endl; // outputs 5
std::cout << "Add three integers: " << add(2, 3, 4) << std::endl; // outputs 9
std::cout << "Add two doubles: " << add(2.5, 3.5) << std::endl; // outputs 6.0
return 0;
}
Operator overloading allows you to redefine the way operators work for user-defined types (like classes). This can make your code more intuitive when working with complex data types.
#include
class Complex {
public:
float real;
float imag;
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overload the + operator
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
};
int main() {
Complex c1(2.0, 3.0);
Complex c2(4.0, 5.0);
Complex c3 = c1 + c2; // Uses overloaded + operator.
std::cout << "Result: " << c3.real << " + " << c3.imag << "i" << std::endl; // Outputs: Result: 6.0 + 8.0i
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?