Operator overloading - 2D Point

Operator overloading 2DPoint

Create a 2DPoint struct with member variables x and y. Overload the + and - operators to add and subtract two Point objects by summing or subtracting their x and y values. Add a single float value constructor to add support for subtracting single floats. Also, add * and / operators that take a float value and multiply or divide the x and y values.

Answer

#include <iostream>

struct 2DPoint {
    float x;
    float y;

    // Default constructor
    2DPoint() : x(0), y(0) {}

    // Constructor with parameters
    2DPoint(float xVal, float yVal) : x(xVal), y(yVal) {}

    // Constructor with single float value
    2DPoint(float value) : x(value), y(value) {}

    // Overload + operator
    2DPoint operator+(const 2DPoint& other) const {
        return 2DPoint(x + other.x, y + other.y);
    }

    // Overload - operator (Point - Point)
    2DPoint operator-(const 2DPoint& other) const {
        return 2DPoint(x - other.x, y - other.y);
    }

    // Overload * operator
    2DPoint operator*(float value) const {
        return 2DPoint(x * value, y * value);
    }

    // Overload / operator
    2DPoint operator/(float value) const {
        return 2DPoint(x / value, y / value);
    }

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

int main() {
    2DPoint point1(2.0, 3.0);
    2DPoint point2(4.0, 5.0);

    // Adding two points
    2DPoint resultAdd = point1 + point2;
    std::cout << "Addition result: ";
    resultAdd.display();

    // Subtracting two points
    2DPoint resultSub = point1 - point2;
    std::cout << "Subtraction result (Point - Point): ";
    resultSub.display();

    // Subtracting a float from a point
    2DPoint resultSubFloat = point1 - 1.0f;
    std::cout << "Subtraction result (Point - float): ";
    resultSubFloat.display();

    // Multiplying a point by a float
    2DPoint resultMul = point1 * 2.0f;
    std::cout << "Multiplication result: ";
    resultMul.display();

    // Dividing a point by a float
    2DPoint resultDiv = point1 / 2.0f;
    std::cout << "Division result: ";
    resultDiv.display();

    return 0;
}
Questions