+ 2

Why can't I print "count"?

I'm able to do it from the constructor, but not a member function. Why? How can I make it work? https://code.sololearn.com/cVzodsR6ZNTt/?ref=app

5th Mar 2019, 10:34 PM
Daniel Cooper
Daniel Cooper - avatar
4 Answers
+ 3
Because count is declared inside the constructor, therefore it is only accessible inside the constructor. If you want it to belong to the whole class you should declare it just like all other class variables, but with static added to it. Initialize it outside the class but not inside the constructor. e.g. class T { public: static int foo; }; int T::foo = 0;
5th Mar 2019, 11:08 PM
Dennis
Dennis - avatar
+ 3
I agree with Dennis. There is also one simple solution to get output you want. (it works but you should listen to Dennis, you should create id variable.) This is part of your code (lines 65-67): Person Joshya("Joshya","Cooper", 20, HisBd); Daniel.printInfo(); Joshya.printInfo(); just cut Daniel.printInfo(); and paste it above Person Joshya("Joshya","Cooper", 20, HisBd); ... and it will work, because you first call constructor and in your constructor count++ is now = 1 then you print info of your first object. After that you create a new object by calling constructor and now count is = 2, then you print info of your second object. I am coming from Java world, but the concept is similar.
6th Mar 2019, 12:17 AM
voja
voja - avatar
+ 2
I can only get it to print the final count of all objects of the class. I need it to print the number of each person object let's say I make 2 person objects Person a(params) Person b(params) now if I print the data, I should get something like "Person #1" -param data- "Person #2" -param data- (param data being names and age and other data)
5th Mar 2019, 11:52 PM
Daniel Cooper
Daniel Cooper - avatar
+ 2
Yea, you need another variable inside the class called something like id, and assign that id with the value of that static variable inside the constructor before you increment that counter. You print the id, not the counter.
6th Mar 2019, 12:00 AM
Dennis
Dennis - avatar