[Solved] Why is the output of this code is 22? [duplicate]


It’s simple. You create a which has *val set to 0.

Then you create b via b = a, which invokes copy constuctor. The copy constructor calls a.get().

A::get() increments the value pointed by val by 1 and then returns it. So a gets *val set to 1, and b gets back this value and also sets its own *val to 1.

Then you print both by using get() which again increases each before returning. So you get 2 from both gets on cout << a.get() << b.get();.

I don’t know the reason why val is a int* instead of just int it only obfuscates the code, and makes it harder to grasp for a beginner.

4

solved Why is the output of this code is 22? [duplicate]