how can one create a class with a constructor that counts the number of people who are alive,if i have 10 people it should count the quantity of people who are alive,people should be objects in this example,lets say i have a class man like this below
class man{
private:
string name;
man(string name=""){
cout<<"there 10 people alive"<<endl;
~man(){}
};
int main(){
}
i am getting confused on how to go about it,i really need a simple example i want to use the set and get methods
The sane version of this would be to store your
manobjects in a collection, say astd::vector. From thisstd::vector, you could usesizeon the vector to fetch the number of items contained in it.Otherwise, go with a solution that doesn’t make sense in this context, which would be to store a
staticvariable that is increased in theconstructorand decreased in thedestructor.By the way, your
manclass has a few mistakes, theconstructoris private and you’re missing brackets… here’s a simple version of what you’re looking for:Edit:
Lets add how to handle it if you’re going with a static variable… see the following scenario (I collapsed much of the brackets just to make it shorter)
See the following code:
The output to that will be
Wait… what?!? Where did we lose a man? Well, this happened in the vector resizing, since we didn’t define a
copy constructor, the compiler did it for us, but the compiler wasn’t aware that we wanted to incrementsCount, so when the vector resized, new objects were created, old ones destructed, andsCountdidn’t get updated properly.By changing our
manclass to:We now have:
But why?!?. There are 2
manobjects on the stack,BobandJimmy. Then there’s 2 copy of these these objects instd::vector<man> menbecause the vector contains “objects of typeman“.If we changed this to pointers:
We now have the following output, which is what we’re looking for:
Hope this clears things up for you!