I'm doing an exercise and I cannot understand why the following code returns:
Program start, before f() -- number of objects: 0
After f(), before g() -- number of objects: 0
After g(), before h() -- number of objects: -1
After h(), program end -- number of objects: -1
There is nothing wrong with f() and I understand everything happening there. However, I cannot figure out how the constructor and the destructor are called in g() and h(). Thank :)
Code:
class Counted {
public:
Counted();
~Counted();
static int getNbrObj();
private:
static int nbrObj;
};
int Counted::nbrObj = 0;
Counted::Counted() {
nbrObj++;
}
Counted::~Counted() {
nbrObj--;
}
int Counted::getNbrObj() {
return nbrObj;
}
void f() {
Counted c;
Counted* pc = new Counted;
delete pc;
}
void g() {
Counted c1;
Counted c2 = c1;
}
void h() {
Counted c1;
Counted c2;
c2 = c1;
}
using namespace std;
void print_nbr_objects(const string& msg) {
cout << msg << " -- number of objects: "
<< Counted::getNbrObj() << endl;
}
int main() {
print_nbr_objects("Program start, before f()");
f();
print_nbr_objects("After f(), before g() ");
g();
print_nbr_objects("After g(), before h() ");
h();
print_nbr_objects("After h(), program end ");
}