Problem with pointers, need help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <conio>
class sum
	{
   private:
   	int* a;
   public:
   	sum()
      	{
         a = new int;
         *a = 0;
         }
      sum(int b)
      	{
         a = new int;
         *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.
Last edited on
come on ... not even 1 reply :(
What, you're already complaining after just ten minutes? Also, use code tags if you're expecting anyone to read that.
Last edited on
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.

Topic archived. No new replies allowed.