Operator Overloading

This example shows how to overload the + operator for a custom class.

cppCopy code#include <iostream>

class Vector {
public:
    Vector(int x, int y) : x(x), y(y) {}

    // Overloading the + operator
    Vector operator+(const Vector& other) {
        return Vector(x + other.x, y + other.y);
    }

    void display() {
        std::cout << "Vector(" << x << ", " << y << ")" << std::endl;
    }

private:
    int x, y;
};

int main() {
    Vector v1(1, 2);
    Vector v2(3, 4);
    Vector v3 = v1 + v2; // Calls operator+
    v3.display(); // Output: Vector(4, 6)
    return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *