Count the number of class

Hello everyone,

assuming i have the Class Animals and i have created 3 instances of animals:

Animals cat;
Animals dog;
Animals bird;

how can i count and interate through the number of Animals accessing each (dog, cat and bird) property and methods?

Thank you very much
store them in array or vector.
Thank you, already done this.

There's a way to count the instances of a class?
use a static int member in your Animals class. increment this by one in your constructor.
http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
... and if it's important that you can identify which member of the vector is cat, or dog, or whatever, you could use an enum to define meaningful sumbols, e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
enum AnimalType
{
  CAT = 0,  // Don't actually need the "= 0", but it makes things clear
  DOG,
  BIRD,

  // Define any other symbols here

  NUM_ANIMALS // Final symbol in the enum gives you the number of previous symbols
};

Animals cat;
Animals dog;
Animals bird;

std::vector<Animals> myAnimals(NUM_ANIMALS);

// Put my animals into the vector
myAnimals[CAT] = cat;
myAnimals[DOG] = dog;
myAnimals[BIRD] = bird;

// Access the details for bird
doSomething(myAnimals[BIRD]);

// Iterate over all animals
for (i = 0; i < NUM_ANIMALS; ++i)
{
  doSomething(myAnimals[i]);
}


EDIT: oops, ninja'd :(
Last edited on
use a static int member in your Animals class. increment this by one in your constructor

... and decrement by one in the destructor. Yes, that's probably obvious, but just in case...
Last edited on
yea :)

edit: i've been doing java for a while, so i'm a bit lax when it comes to cleaning up objects ;)
Last edited on
Do you really need to know how many instances of the class have been created in your program, or just the number that are in the container that you're using? Usually it's the latter, and if you put the objects in a vector then you can use vector::size() to tell how many are in the container.
Thank to all. Very interesting.
I will study carefully
Topic archived. No new replies allowed.