c++ - Destructor called to destruct object before I finish using this object -
in code there's operator+ overloading. in scope, define object ans
, want build , return, seems destructor distructs ans
before can return it, method returns undefined value.
i don't understand wrong? destructor, builder, or in overload of operator+?
here 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 array cells 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 arrays not same size return array of '0', array size cout<<"vectors not same length. can't sum them"<<endl; //test //exit(1); ans.init(); } else{ (int i=0;i<size;i++) ans.set_value_in_index(i,arr[i]+ob.get_value_in_index(i)); } return ans; }
thanks time , help.
your operator+ returns copy of new vector1
class.
original (the 1 declared in beginning of function) gets destroyed @ end of block (before closing bracket }).
the destructor deletes inner array arr
.
copied vector1
object points deleted array.
you should create copy constructor copy inner array well.
vector1(const vector1& _other ){ //copy .arr other 1 one }
Comments
Post a Comment