In operator++ method you create temporary A object which is then destroyed when you return it from the function. There should be also another copy construction and destroying, but RVO elides this one.
When you add log to constructor also you will see better what is going on. I also allowed myself to change printf to cout, for more c++ish coding style.
#include <iostream>
class A {
public:
int value;
A(int value) {
std::cout << "creating " << value << std::endl;
this->value = value;
}
~A() {
std::cout << "destroying " << value << std::endl;
}
A operator ++() { return A(value + 1); }
};
int main() {
A a(1);
std::cout << "before increment: " << a.value << std::endl;
a = ++a;
std::cout << "after increment: " << a.value << std::endl;
return 0;
}
output:
creating 1
before increment: 1
creating 2
destroying 2
after increment: 2
destroying 2
You can also read about canonical implementations of operators overloading:
http://en.cppreference.com/w/cpp/language/operators
operator++ overloading should look like this:
struct X
{
X& operator++() // prefix version
{
// actual increment takes place here
return *this;
}
X operator++(int) // postfix version
{
X tmp(*this); // copy
operator++(); // pre-increment
return tmp; // return old value
}
};