Reputation: 57
I made a simple program making a class and it's 3 objects. I overloaded =, +=, and << operators. The problem is that when i use = and += operators, the destructors get called after the execution of the function.
As far as I know, destructors are called when an object goes out of scope or when the 'delete' operator is used. But, in my case, it's none of the two. I looked into some other websites, like the oficial C++ website, but, I couldn't get the answer. Here's the code that I wrote.
#include<iostream>
using namespace std;
class Class
{
int flag,name;
public:
Class(int y,int z)
{
flag=y;
name=z;
}
Class& operator=(Class);
Class operator+=(Class);
friend ostream& operator<<(ostream&,Class&);
~Class()
{
cout<<"Destroying "<<flag<<endl;
}
};
int main()
{
Class C1(1,80),C2(2,90),C3(3,100);
cout<<C1<<C2<<C3<<endl;
C1=C2=C3;
cout<<C1<<C2<<C3<<endl;
C3=C1+=C2;
cout<<C1<<C2<<C3<<endl;
return 0;
}
Class& Class::operator=(Class x)
{
name=x.name;
return *this;
}
Class Class::operator+=(Class x)
{
name+=x.name;
return *this;
}
ostream& operator<<(ostream& o,Class& c)
{
o<<c.name;
return o;
}
The output I'm getting is this:
8090100
Destroying 2
Destroying 3
100100100
Destroying 1
Destroying 2
200100200
Destroying 3
Destroying 2
Destroying 1
Destructors of C2,C3 and then C1,C2 are called in the process even when they're not out of scope. I tried this program by changing the function names and even changing the return type to 'void', but still, the destructors were called. I compiled this program in GCC-4.9.3.
I would appreciate any help on this topic, and do forgive me if my question is too silly.
Upvotes: 2
Views: 222
Reputation: 1479
Please refer to Class& operator=(Class);
and Class operator+=(Class);
They take objects as parameters (not references). Thus, destroying those temp objects invokes the destructor.
Just noticed more comments above explaining this... :)
Upvotes: 0
Reputation: 65620
Your operators take the argument by value, making a copy which will be destructed when the function ends.
If you don't want to create a copy, take the argument by const reference. As interjay pointed out, operator+=
should also return a reference rather than copying *this
:
Class& operator=(const Class&);
Class& operator+=(const Class&);
Upvotes: 10
Reputation: 32904
Class& Class::operator=(Class x);
C1=C2=C3;
When you do C2 = C3
notice that the operator=
takes the right hand side by value, so a copy of C3
gets created (x
); its data is copied to C2
's. When the function operator=
returns, the parameter x
goes out of scope and destroyed. This happens twice: once for C2=C3
and once for C1=C2
, so you see both. This also explains the behaviour of operator+=
.
If you want to avoid that take x
by reference, as shown in Tartan's answer.
Upvotes: 3