How to loop through an array of different types of classes

I have the following classes in my c++ program:

  • game_entity
  • game_creature which inherits from game_entity

I plan to have more classes that either inherit from game_entity, game_creature, or even some other lower classes.

I also have an array of type game_entity, which contains both game_entity instances, and game_creature instances. Now my problem is this: I try to loop through the array when it is passed to a function, but when it gets to a game_creature object, it does not increment the pointer by enough using subscript form.

For example:

If the first object is a game_creature (which has more fields than a game_entity), it will access the first 3 fields (which are the same on game_creature as on game_entity) just fine, but when I do array[1], it will access the value of the second two ints in the first game_creature as the first two ints in the second game_creature object.

This would mean that if I have a game_creature with x = 1, y = 2, sprite* = Something, movespeed = 5, and health = 25, then it would access x and y of the second game_creature object as 5 and 25, which is actually the movespeed and health of the first game_creature.

I think this is because the memory that the pointer is pointing to for the x and y of a "game_entity" is actually where the movespeed and health of a "game_creature" are. However, I don't know how to make an array of game_entities, so it can hold any type of object that would be on the grid of my game, but still have it access the proper fields and increment the pointer by enough each time.

Any help is appreciated.


You can create an array of pointers to your base class, and that will "hold" any of your entities, but you can't create an array of the base class and assume it'll hold your sub-classes as well, because in C/C++, arrays are fixed-length, and each element is a fixed amount. Even if you used a vector or something, it still wouldn't work, as each element would be purely the base class.

In C++11, you could use a tuple, but it's probably not what you're looking for. I'd use an array of pointers (or better yet, a container class of smart pointers) to the base class, and iterate through that.

You can't have an array of different classes. If you try to put a derived class into a base class array you will get slicing. You need to use an array of pointers to base class.

You should use polymorphism, and use C++ standard support for it (using virtual base classes to iterate through "instance-of"-pointers' containers).

Need Your Help

Adding two timestamps in SQL

sql sql-server-2005

I have two fields in sql date1 varchar(4) and date2 varchar(4). The date format is just HHmm where HH is the hours and mm is the minutes.