#include<iostream>
using namespace std;
class test
{
int a;
public:
test()
{
a=0;
}
test operator ++(int)
{ a++;
return *this;
}
void display()
{
cout<<a;
}
~test() {
cout << "DES" << endl;
}
};
int main()
{
test t,t1;
t1 = t++;
t.display();
system("pause");
}
The output that i get is :
DES
1Press any key to continue...
DES
DES
Why does the destructor work before ?
The expression t++ results in a temporary object of type test, since operator++(int) returns by value[*]. You're seeing the destruction of that temporary, after operator= has finished using it to assign the new value of t1.
[*] Normally this should contain the value of t prior to it being incremented, but in your implementation it's just a copy of the object after incrementing, which you create by doing return *this;. So your function body is more suitable for operator++() (pre-increment) rather than operator++(int) (post-increment).
Because
t1 = t++;
creates a temporary object that will be destroyed by the end of the expression (;).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With