Can someone explain to me why is this the output of this code in C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain to me why is this the output of this code in C++?

Can someone explain to me why is this the output of this code in C++? The question that is asked is what is the output that is written out by the destructors of these objects (a,b,c,d,e,f)? This is part of a course test, and the good answer is supposed to be: for a: 3:0. for b: 3:1. for c: 2:2. for d: 2:1. for e: 3:1. for f: 3:2. Can someone explain how this question can be solved without compiling the code? Thank you class A { public : static int o; int oo; A ( ) :oo(o++) {}; A (const A& po ) : oo(po .oo + 1) {}; ~A () {cout << o << ' : ' << oo << '\n' ;} }; int A ::o = 0; int main ( ) { A a A b(a); { A c (b ); A d; } A e(a); A f; return 0; }

11th May 2023, 5:26 PM
BMN16
4 Answers
+ 2
ugh, this is some ugly code. Gonna have to do it step by step, so bear with me. Obviously start at the tildes~ for your destructors: class A's output in printf would look like ("%d:%d\n", o, oo) so, o is initialized to 0, when A is defined, and is static (ie shared) Constructing an A object with no arguments sets oo = o++, which is to say oo=o followed by o+=1. Constructing an A object with another A, referred to as po , as its argument sets oo = po .oo +1 so A a: o = 1, a.oo = 0 A b(a): o = 1, b.oo = 1 scope begins: A c(b): o = 1, c.oo = 2 A d: o = 2, d.oo = 1 scope ends, c and d are deconstructed. output o:c.oo and o:d.oo, which are 2:2 and 2:1 respectively A e(a): o = 2, e.oo = 1 A f: o = 3, f.oo = 2 main ends; output o:a.oo, o:b.oo, o:e.oo, and o:f.oo, which are 3:0, 3:1, 3:1, and 3:2 respectively. This matches the correct answer so I probably didn't screw anything up. phew 😅
11th May 2023, 8:41 PM
Orin Cook
Orin Cook - avatar
+ 1
those ooooooo's😅. also, the code would not compile because you have some errors. ' : ' should be ':' or " : ", and missing semicolon on A a But yes, it's a very good explanation by Orin Cook. I can't help but run it to see if that is indeed the case. Let the code explain itself. https://code.sololearn.com/ckdmaaWcm5OR/?ref=app
12th May 2023, 5:57 AM
Bob_Li
Bob_Li - avatar
0
the complexity of the code makes it hard to visualise everything in mind. try putting it in some debugger and step over each line to better understand it.
11th May 2023, 5:28 PM
Sharique
0
Thank you so much!
12th May 2023, 4:14 AM
BMN16