Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructor works before . How?

#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 ?

like image 896
program-o-steve Avatar asked Nov 30 '22 07:11

program-o-steve


2 Answers

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).

like image 72
Steve Jessop Avatar answered Dec 05 '22 07:12

Steve Jessop


Because

t1 = t++;

creates a temporary object that will be destroyed by the end of the expression (;).

like image 35
PlasmaHH Avatar answered Dec 05 '22 06:12

PlasmaHH