0

Result of the code step by step in C++

Hello, can someone please help me through this code step by step, how does it come to the solution (which is at the end of the code at the bettem of the page)? Thank you https://ibb.co/ZMDqGDc class C1 { static int sa; int a; public: C1(int _a) : a(sa) { sa=_a;} ~C1() { ++sa; cout << a;} }; class C2 { static int sb; int b; public: C2() : b(++sb) {} ~C2() {cout << b;} }; int C1::sa=1; int C2::sb=0; { C1 a1(2); C2 b1; C1 a2(1); } //1 cout << endl; { C2 b1; C1 a1(7); c2 b2; } // 2 cout << endl; { C2 b1, b2; C1 a1(4); }//3 cout << endl; Results are: //1: 2,1,1 //2: 3,3,2 //3: 8,5,4

31st May 2023, 5:12 AM
BMN16
6 Answers
+ 3
can you copy paste the code here?
31st May 2023, 7:33 AM
Jared
Jared - avatar
0
Yes, of course. class C1 { static int sa; int a; public: C1(int _a) : a(sa) { sa=_a;} ~C1() { ++sa; cout << a;} }; class C2 { static int sb; int b; public: C2() : b(++sb) {} ~C2() {cout << b;} }; int C1::sa=1; int C2::sb=0; { C1 a1(2); C2 b1; C1 a2(1); } //1 cout << endl; { C2 b1; C1 a1(7); c2 b2; } // 2 cout << endl; { C2 b1, b2; C1 a1(4); }//3 cout << endl; Results are: //1: 2,1,1 //2: 3,3,2 //3: 8,5,4
31st May 2023, 9:41 AM
BMN16
0
Ok, so: sa and sb are static, and start at 1 and 0 respectively When you create any C1, it sets its own this.a = sa, and then changes the shared sa to the argument passed to it. When it is destroyed (eg by going out of scope), it increments the shared sa and prints its own a. When you create a C2, it first increments the shared sb, and then sets b = sb. When destroyed, it just prints b. So: Scope 1: C1 a1(2): a1.a is 1, sa is 2 C2 b1: sb is 1, b1.b is 1 C1 a2(1): a2.a is 2, sa is 1 Scope ends, prints (in LIFO order) a2.a, b1.b, and a1.a == 211 sa is also incremented twice by C1 destructors, so sa is now 3 Scope 2: b1: sb is 2, b1.b is 2 a1(7): a1.a is 3, sa is 7 b2: sb is 3, b2.b is 3 Scope ends, print 332, increment sa (now 8) Scope 3: b1: sb is 4, b1.b is 4 b2: sb is 5, b2.b is 5 a1(4): a1.a is 8, sa is 4 Scope ends, print 854 (sa is incremented but it doesn't matter) final output: 211 332 854
31st May 2023, 2:18 PM
Orin Cook
Orin Cook - avatar
0
Thank you very much. The part which I have problem with is the following: C1 a2(1): a2.a is 2, sa is 1 I understand why sa is 1 here, I just don't understand exactly why a2.a is 2.
31st May 2023, 6:38 PM
BMN16
0
Because of the way it's written, the C1 constructor sets a=sa before doing anything else, as part of the initialization of the instance, and then sa = _a second, when the constructor actually executes.
31st May 2023, 7:19 PM
Orin Cook
Orin Cook - avatar
0
Okay, now I get the whole picture. Thank you so much!
1st Jun 2023, 5:03 AM
BMN16