c++ - Why is the output of this code is 22? -
c++ - Why is the output of this code is 22? -
this question has reply here:
why output of code 21 , not 12? [duplicate] 2 answers#include <iostream> using namespace std; class { int *val; public: a() { val = new int; *val = 0; } a(a &a) { val = new int; *val = a.get(); } int get() { homecoming ++(*val); } }; int main() { a,b = a; cout << a.get() << b.get(); homecoming 0; }
i have problem working out. getting confused on how *val gives output of 22 both object.
it's simple. create a
has *val
set 0
.
then create b
via b = a
, invokes re-create constuctor. re-create constructor calls a.get()
.
a::get()
increments value pointed val
1 , returns it. a
gets *val
set 1
, , b
gets value , sets own *val
1
.
then print both using get()
1 time again increases each before returning. 2
both get
s on cout << a.get() << b.get();
.
i don't know reason why val
int*
instead of int
obfuscates code, , makes harder grasp beginner.
c++
Comments
Post a Comment