### Help! I need code explanation

Hello, guys!! I have to answer what will the variable values be in the following code, but I do not understand it.

 ``12345678910111213141516171819202122232425262728293031323334`` `````` #include using namespace std; class TstA{ static int c; double d; int n; public: TstA(int x=1):d(x*2.){n=c--;} TstA(TstA & t){ d=t.d;n=t.n*10-c--; } ~TstA(){ cout<<"End#"<
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.
 ``1234567891011121314`` `````` 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<

UPD: Ooops, my bad about undeclared c, i just some reformated code for better readability and got an error.
Last edited on
Here is the code with indenting and some output in the constructors and destructor.
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455`` ``````#include using namespace std; class TstA { static int 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; } static int 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.
 ```TstA(1) c=0 this=0xffffcbb0 TstA(1) c=-1 this=0xffffcbc0 TstA(5) c=-2 this=0xffffcba0 TstA(0xffffcba0) c=-3 this=0xffffcb90 -4 Tst#0: 2 Tst#-1: 2 TstA(0xffffcb90) c=-4 this=0xffffcbd0 Tst#-166: 10 destroy 0xffffcbd0 destroy 0xffffcb90 destroy 0xffffcba0 -2 destroy 0xffffcbc0 destroy 0xffffcbb0 ```

Line 53: TstA objects `a` and `c` created at line 48 get destroyed here.