How do I overload functions and operators?

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

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.

Example of Function Overloading:

#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

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.

Example of Operator Overloading:

#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; }

C++ function overloading operator overloading programming C++ examples