0

I am trying to figure out how to correctly overload operators.

Q#1: Is there something wrong with my code/can it be written better?

Q#2: Is it ok to have this in header file only?

// Vector2.hpp:

template <class T>
class Vector2 {
   public:
    Vector2(T x, T y) {
        this->x = x;
        this->y = y;
    }
    T x;
    T y;

    Vector2<T> operator+=(const Vector2<T>& other) {
        return Vector2<T>(this->x + other.x, this->y + other.y);
    }

    Vector2<T> operator+(const Vector2<T>& other) {
        return Vector2<T>(this->x + other.x, this->y + other.y);
    }
};
Etwus
  • 549
  • 5
  • 15
  • 1
    Operator + should be a free, non-member function, possibly implemented using operator +=. –  Sep 05 '19 at 20:51
  • 2
    Not quite. `+=` should modify and return `this`, not a temporary object. The return type should also be `Vector2 &`. Handy reading: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Sep 05 '19 at 20:51
  • 2
    *Is it ok to have this in header file only?* [You will have problems making a template that is NOT header only.](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – user4581301 Sep 05 '19 at 20:58

0 Answers0