- 2

Can someone explain this code to me

class abc{ public: static int x; int i; abc(){i++x;} }; int abc::x; main(){ abc m,n, p; cout<<m.x <<m.i; } The answer is: 31

27th Nov 2020, 6:25 PM
Miosotis
1 Answer
+ 3
You are missing an assignment in the constructor of "abc" and a return type for main(), but other than that, the main aspect is the difference between normal and static variables. If you are not familiar with static variables, I suggest you to look it up, e.g. here https://en.cppreference.com/w/cpp/language/static The code itself is pretty straightforward, each instantiation of "abc" will increment the counter 'x' by one, and the 'i' field of the constructed object is assigned the new value of 'x'. Since you instantiate three objects, m.i will be 1, n.1 = 2, and p.i is going to be 3. The value of 'x' will be the total number of objects created, i.e. 3 as well. You can think of it as an ID system, where the class keeps track of how many objects are created from it, and assigns each object a unique ID.
27th Nov 2020, 8:17 PM
Shadow
Shadow - avatar