Reputation: 119
I am trying to track how many object is created of a given class. If I overload the operator ++ in the class, the destructor is called but I don't know why. To be more specific:
class num{
public:
virtual void setValue(int)=0;
static int db;
num(){}
~num(){}
};
int num::db = 0;
class int32: public num{
public:
// GET
int getValue();
// SET
void setValue(int f);
// constructor
int32()
{
cout << "Construction..."<<endl;
this->value = 0;num::db++;
}
// destructor
~int32()
{
cout << "destruction..."<<endl;
num::db--;
}
// operators
int32 operator++(int);
int32 operator++(void);
protected:
int value;
};
int32 int32::operator ++()
{
this->value++;
return *this;
}
int32 int32::operator ++(int)
{
this->value++;
return *this;
}
int main()
{
int32 i;
i.setValue(20);
cout << (i++).getValue()<<endl;
cout << (++i).getValue()<<endl;
cout << num::db;
cout << endl << "End of execution.";
return 1;
}
The result is: Construction... 21 destruction... 22 destruction... -1 End of execution.destruction...
So after ++i and i++ a destructor is called, but why?
Thanks a lot!
Upvotes: 1
Views: 1848
Reputation: 1090
It is because your "operator++()" methods both return a copy of a "int32". Thus for every call a new instance is created and returned.
Upvotes: 0
Reputation: 22291
You are returning a copy of the object in the ++ operator.
each time you call return *this
you actually create a copy of the object which is passed to the calling code.
Upvotes: 1
Reputation: 409472
It's because you return a copy. You would want to create a copy constructor.
Upvotes: 3