I am Trying to make an overload in "+" operator. The problem is I have to create a brand new object that will contain the sum, but when I try to return it, it gets deleted.(I think its because the object is locally created, so the system makes a shallow copy, and when it gets out of scope its content is deleted) How can I avoid it getting deleted?
The operator overload
Thing Thing::operator+(const Thing& thing){
Thing sum;
sum.attribute=this->attribute+thing.attribute;
sum.things= new int[sum.attribute];
static int k=0;
for(int i=0;i<this->attribute;i++){
std::cout<<this->things[i];
sum.things[k]=this->things[i];
}
for(int j=0;j<thing.attribute;j++){
std::cout<<thing.things[j];
sum.things[k]=thing.things[j];
}
return sum;}
The main
int main(){
Thing one(1,1);
Thing two(2,2);
Thing three;
three = one+two;
std::cout<<"One"<<std::endl;
std::cout<<one.getAttribute()<<std::endl;
one.showVec();
std::cout<<"Two"<<std::endl;
std::cout<<two.getAttribute()<<std::endl;
two.showVec();
std::cout<<"Three"<<std::endl;
std::cout<<three.getAttribute()<<std::endl;
three.showVec();
Copy constructor
Thing::Thing(const Thing& stuff){
std::cout<<"Copy"<<std::endl;
this->attribute=stuff.attribute;
this->things = new int[this->attribute];
for(int i =0;i<attribute;i++)
this->things[i]=stuff.things[i];
}
The class
class Thing {
private:
int attribute;
int* things;
public:
//constructors
Thing(int=0,int=0);
Thing(const Thing&);
//destructor
~Thing();
//operators
Thing operator+(const Thing&);
//getters
int getAttribute();
//functions
void showVec();
};
My output
Default
Default
Default
Default
122Destructor
One
1
1
Two
2
2 2
Three
3
17002888 16974016 0 (The problem is here)
Destructor
Destructor
Destructor