C++ Operator Overloading

Operator overloading in C++ enables the redefining of operators like +, -, *, /, ==,!=,, >, etc. to work with user-defined data types. The behaviour of these operators when applied to objects belonging to a class can therefore be specified.

Take the class Vector, for instance, which represents a 2D vector with x and y coordinates. To combine two Vector objects, we can overload the + operator as seen below:

#include <iostream>

class Vector {
public:
    Vector(double x = 0, double y = 0) : x(x), y(y) {}
    double getX() const { return x; }
    double getY() const { return y; }
    Vector operator+(const Vector& other) const {
        return Vector(x + other.x, y + other.y);
    }
private:
    double x, y;
};

int main() {
    Vector v1(1, 2), v2(3, 4);
    Vector v3 = v1 + v2;
    std::cout << "(" << v3.getX() << ", " << v3.getY() << ")" << std::endl;
    return 0;
}

Output:

(4, 6)

The class Vector in this example has two private data members, x and y, and a function Object() { [native code] } that accepts two optional parameters to initialise these data elements. Then, we create a member function called operator+ that accepts a const Vector& as an input and creates a new Vector object by adding the x and y coordinates.

We construct two Vector objects, v1 and v2, and then use the + operator to combine them in the main function. The output is written to the terminal after being stored in a third Vector object v3.

Similar overloading can be done for other operators, including -, *, /, ==,!=,, >, etc., to work with Vector class objects as well as other user-defined data types. By enabling the usage of well-known operators with certain data types, operator overloading can result in more readable and understandable code. But caution must be exercised to prevent unexpected behaviour from being introduced by the overworked operators.