Mikau
March 5th, 2008, 11:28 AM
here is a problem I was unable to find a good solution for in Java. I'm wondering if there's a way you can do it in C++.
Suppose you have a game thats divided into rooms, and each room has an array of pointers to all the objects in the room. Each object in the room is a subclass of GameObject, and so the room has a GameObject pointer array
Now suppose you use inheritance to organize your objects into different groups, such as SolidObject (objects you can't walk through) Enemies, Projectiles, items, etc. and suppose you want to get all the objects in the room (contained in the GameObject array) that are members of one of those groups (all instances of that class, and its subclasses).
I would be nice to write a function to do this, you basically need to check each item in the array to see if it is an instance of the class you are looking for. The only problem is, the mechanism that allows you to do this, namely 'instance_of' in java, 'dynamic_cast' in C++, both take a class name as an argument, and class names (to my knowledge) cannot be passed as an argument to a function. Therefore, every time I need to get all the members of a base class from the array, i have to write a for loop right then and there so I can explicitly give the class name with the cast operation. This is how I was forced to do it in java. Is there a better way this can be done in C++?
Suppose you have a game thats divided into rooms, and each room has an array of pointers to all the objects in the room. Each object in the room is a subclass of GameObject, and so the room has a GameObject pointer array
Now suppose you use inheritance to organize your objects into different groups, such as SolidObject (objects you can't walk through) Enemies, Projectiles, items, etc. and suppose you want to get all the objects in the room (contained in the GameObject array) that are members of one of those groups (all instances of that class, and its subclasses).
I would be nice to write a function to do this, you basically need to check each item in the array to see if it is an instance of the class you are looking for. The only problem is, the mechanism that allows you to do this, namely 'instance_of' in java, 'dynamic_cast' in C++, both take a class name as an argument, and class names (to my knowledge) cannot be passed as an argument to a function. Therefore, every time I need to get all the members of a base class from the array, i have to write a for loop right then and there so I can explicitly give the class name with the cast operation. This is how I was forced to do it in java. Is there a better way this can be done in C++?