Operator Overloading in C++

  1. How operators work

    Operators are symbols that makes some operations. They are just functions.

  2. Operator Overloading

    Operator overloading is adding new funcitonality to the operators. To overload operator in class you make a method named operator followed by an operator you want to overload and then parameters. For example we have a vector class and we need to add two vectors. We can overload plus operator to make that.

    struct Vec2{
        float X, Y;
        Vec2(float x, float y) : X(x), Y(y){}
        Vec2 add(const Vec2& other) const {
            return operator+(other); // calls operator '+'
        }
        Vec2 operator+(const Vec2& other) const {
            return Vec2(X + other.X, Y + other.Y); // returns added vectors into a new vector
        }
    };
    Vec2 position(0, 0);
    Vec2 direction(0, 1.0f);
     
    Vec2 result = position + direction;