So, every object of class TstA has two fields - d and n. Besides class TstA contains static field that set with initial value = 0 and decrements when new object is created and increments when one of current objects is destroyed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
TstA b[2]; // creates two objects with defalult constructor
// c = 0, so for first one d = 2.0, n = 0, c becomes -1
// c = -1, so for second one d = 2.0, n = -1, c becomes -2
TstA a(5); // creates one more object with default constructor but with user-defined value
// instead of default. c = -2, so for this one d = 10.0, n = -2, c becomes -3
TstA = c; // creates last object with copy constuctor.
// c = -3, so d = 10.0 and n = -17, c becomes -4;
for(int i=0;i<2;i++)b[i].show();
f(c);
// this lines prints values described before
// Then we leave separated scope {} and all static objects will be removed with their //destructors so we getting next cout messages and c is incremented twice.
//-4 + 2 = -2
//So c = -2 and last cout proves it.
cout<<TstA::status()<<endl;
UPD: Ooops, my bad about undeclared c, i just some reformated code for better readability and got an error.
#include<iostream>
usingnamespace std;
class TstA
{
staticint c;
double d;
int n;
public:
TstA(int x = 1):d(x * 2.) {
cout << "TstA(" << x << ") c=" << c << " this=" << this << '\n';
n = c--;
}
TstA(TstA & t)
{
cout << "TstA(" << &t << ") c=" << c << " this=" << this << '\n';
d = t.d;
n = t.n * 10 - c--;
}
~TstA() {
cout << "destroy " << this << endl;
c++;
}
void show()
{
cout << "Tst#" << n << ": " << d << endl;
}
staticint status()
{
return c;
}
};
int TstA::c = 0;
void
f(TstA t)
{
t.show();
}
int
main()
{
TstA b[2];
{
TstA a(5), c = a;
cout << c.status() << endl;
for (int i = 0; i < 2; i++)
b[i].show();
f(c);
}
cout << TstA::status() << endl;
}
And here is the output. Note that the values for "this" will be different on your system, just use them to see what object is getting passed around where.
Some comments in addition to DonRumata's (using my line numbers):
Line 38: notice that t is passed by value. That means the copy constructor gets called, and the destructor gets called when f() exits.
Line 53: TstA objects a and c created at line 48 get destroyed here.