0
class TwoDVector {
   private:
       double a, b;
   public:
       TwoDVector(double a, double b);
       TwoDvector operator+(TwoDVector &vec1);
};
TwoDVector::TwoDVector (double a, double b) {
    this->a = a; this->b = b;
}
TwoDVector TwoDVector::operator+(TwoDVector &vec1) {
    TwoDVector vec2, vec3;
    vec3.a = vec2.a + vec1.a;
    vec3.b = vec1.b + vec2.b;

    return vec3;
}

int main () {
   TwoDVector td1(3, 5), td2(5,6);
   td1.operator+(td2); // isn't this how you're supposed to call this function?

I want to return an object in this function. I have been restricted to pass only one parameter to the overloading function, for which I created two objects in the function and used them for calculation. How will I implement this in the main function?

  • 3
    The whole point of operator overloading is to be able to say `td1 + td2`. Also, you need to take the argument to `operator+` by `const&`. – cigien Mar 02 '21 at 15:56
  • **Note:** For this `TwoDVector vec2, vec3;` – you need a default constructor `TwoDVector() {}`. – Rohan Bari Mar 02 '21 at 15:56
  • The compiler will translate `td1 + td2` as `td1.operator+(td2)`, so it calls your function using only a single argument. – Some programmer dude Mar 02 '21 at 15:57
  • 3
    You already have 2 `TwoDVector` objects in your `operator+` function. `vec1` and `*this`! – Kevin Mar 02 '21 at 15:57
  • I think the linked duplicate contains all information you need to know about operator oveloading, including how to overload a class member `operator+()` function. In your case overloading the binary operator form would be more appropriate, so you should overload this (too). – πάντα ῥεῖ Mar 02 '21 at 15:58
  • Got it! I have a follow up question, tho. What if I don't pass it by `const&`? –  Mar 02 '21 at 15:59
  • @johnapplesead _"What if I don't pass it by const&"_ You'll be unnecessarily restricted to mutable objects passed as parameter. – πάντα ῥεῖ Mar 02 '21 at 16:01
  • If you don't pass the argument by constant reference (i.e. `TwoDVector const&` or `const TwoDVector&`) then you can't do something like `td1 + TwoDVector(a, b)`. – Some programmer dude Mar 02 '21 at 16:01
  • tested it, and got it just right! thanks, guys! –  Mar 02 '21 at 16:02

0 Answers0