0

Im trying to add to objects of class Vector1 Vector1 has:

int dim; // the dimension 
int *x; // the values of all dimensions.

when constructed the user can set the dim and all the values.

Now i try to do this in main:

cout << (vector1 + vector2)[i]; // print x[i] of the sum.

to do this I overloaded both + and [] operators, but Im not sure of how to do + correctly

///////////// At first I thought I would do:

Vector1 &Vector1::operator+(const Vector1 &v2) {
    if (dim == v2.dim) 
    {
        for (int i=0 ; i<dim ; i++)
            x[i] = x[i] + v2.x[i];
    }
    else {
        cout << "Error! Vectors from different dimensions";
        exir(1);
    }
    return *this;
}

but then I realized that Im overwriting Vector1 this way, I want to be able to get the solution without overwriting any data so I thought of this:

Vector1 &Vector1::operator+(const Vector1 &v2) {
    Vector1 temp;
    if (dim == v2.dim) 
    {
        temp.dim = dim;
        int *arr = new int[dim];
        for (int i=0 ; i<dim ; i++)
            arr[i] = x[i] + v2.x[i];
    }
    else 
    {
        cout << "Error! Vectors from different dimensions";
        exit(1);
    }
    return temp;
}

now im not sure if the "temp" vector I'm returning will be deleted after the "cout << ..." line or that it will stay in memory even though Im not using it anymore...

Can someone explain to me how to do this correctly?

Thnx

  • Just do not return by reference. – πάντα ῥεῖ Dec 10 '16 at 15:13
  • Do not return a reference of object that made in the function scope. It will not work, so just return `Vector1` as the result of addition and using move semantics (you can google it with "c++ move") to make some cases efficently – Junyoung Clare Jang Dec 10 '16 at 15:15
  • That duplicate mark doesn't seem quite right. But yes it will die at the end of the function because you have made it on the stack. The easiest solution is @πάνταῥεῖ 's: just take the & from the return value out so it returns a copy as opposed to a reference. – gowrath Dec 10 '16 at 15:15
  • thnx for the reply, first time im asking on stakoverflow and it really helped – Yaniv Benny Dec 10 '16 at 18:14

0 Answers0