Hi All,
I am facing a problem in following code:
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 40 41 42
|
class CVector
{public:
int x;
int y;
static int count;
CVector(){count++;}
CVector(int a,int b)
{
x=a;
y=b;
}
int thisOp(CVector&);
CVector operator +(CVector);
~CVector(){count--;}
};
int CVector::count=0;
int CVector:: thisOp(CVector & a)
{
if (this==&a)
return true;
else return false;
}
CVector CVector::operator +(CVector param)
{
CVector temp;
temp.x=this->x+param.x;
temp.y=this->y+param.y;
cout<<"Count"<<CVector::count<<endl;
return temp;
}
int main()
{
CVector a(1,2), b(2,3),c;
cout<<"Count"<<CVector::count<<endl;
c=a+b;
//cout<<"VAlue in c";
//cout<<endl<<c.x<<"\t"<<c.y<<endl;
return 0;
}
| |
The execution goes like this:
1. Object 'c' is created using default constr. So, count=1.
2. operator+() is called.
3. Object 'temp' is created which is local to operator+(). So, count=2
4. operator+() completely executed. 'temp' is destroyed as it is local to that function. So, count=1.
5. The weird thing is: Destructor is called one more time. And count=0.
I can't understand why object 'c' is getting destroyed on completing operator+() execution?
And if 'c' is not getting destroyed, why the destructor is called twice on complete execution of operator+().
Please advice.