1

In my code there's operator+ overloading. In this scope, I define object ans, which I want to build and return, but it seems that the destructor distructs ans before I can return it, so this method returns some undefined value.

I don't understand where I am wrong? Is it the destructor, the builder, or in my overload of the operator+?

Here is my code:

class vector1{
    int * arr;
int size;
public:
//constructors
vector1(){}
vector1(int n){
    size=n;
    arr= new int[size];
}
//functions
int get_size(){return size;}

void init(){  //initialize all array cells to 0
    for(int i=0;i<size;i++)
        arr[i]=0;
}
int get_value_in_index(int index){
    return arr[index];
}
void set_value_in_index(int i, int num){
    arr[i]=num;
}
int & operator[](int i){
    int default_val=0;
    if (i<0 || i>size){
        cout<<"index not valid"<<endl;
        return default_val;
    }
    return arr[i];
}
vector1 operator+(vector1 & ob);

//destructor
~vector1(){
    delete [] arr;
}
};

vector1 vector1:: operator+(vector1 & ob){
vector1 ans(size);
if (ob.get_size()!=size){  //if the arrays are not the same size return array of     '0', this array size
    cout<<"vectors not the same length. can't sum them"<<endl;
    //test
    //exit(1);
    ans.init();
}
else{
    for (int i=0;i<size;i++)
        ans.set_value_in_index(i,arr[i]+ob.get_value_in_index(i));
}
return ans;
}

Thanks for your time and help.

makc
  • 2,569
  • 1
  • 18
  • 28
naama
  • 11
  • 3

3 Answers3

5

Your operator+ returns a copy of a new vector1 class.
But the original (the one declared in the beginning of the function) gets destroyed at the end of the block (before the closing bracket }).

The destructor then deletes the inner array arr.
So the copied vector1 object points to a deleted array.

You should create a copy constructor that will copy the inner array as well.

vector1(const vector1& _other ){
 //copy .arr from the other one to this one
}
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
1

When you return from operator+ a shallow copy of ans is made leaving two instances of vector1 pointing to the same data. When the first instance goes out of scope it deletes the data that both point to. To correct this you need to add a copy constructor that makes deep copies to vector1

vector1(const vector1& other)
{
    // make a deep copy from "other.
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
0

You didn't define a copy constructor so a default one was created by the compiler.

your operator+ returns a shallow copy of your vector. when ans goes out of scope at the end of the operator it takes the data with him.

please read more about What is The Rule of Three?

Community
  • 1
  • 1
makc
  • 2,569
  • 1
  • 18
  • 28