#include <iostream>
#include <conio>
class sum
{
private:
int* a;
public:
sum()
{
a = newint;
*a = 0;
}
sum(int b)
{
a = newint;
*a = b;
}
~sum()
{
delete a;
cout<<"destructor ";
}
sum operator+(sum s) const
{
return sum( *a + *(s.a) );
}
void display() const
{
cout<<*a<<endl;
}
};
int main()
{
sum s1(5),s2(2),s3;
s3 = s1+s2;
s3.display();
getch();
}
output : destructor destructor 1445588
the program is displaying garbage value as sum, this is because the destructor is called when the operator+ function is called. Please help me correct this.
The destructor is being called for the copy passed as a parameter to you + operator and again for the copy returned after the invocation of the default assignment.
You should implement a copy constructor and override the assignment operator. This is the purpose of the exercise.