Skip to main content
gamedev.net
🔒 Locked

runtime type casting

Started by steve coward Nov 30, 2001 at 5:50 PM 4 replies 350+ views
Original Post
steve coward
steve coward
I am developing a 2D game based on Red Alert game. I have a tank class and an infantry class, among others. I want to be able to pass into a subroutine a pointer to either a instance of the tank class or an instance of the infantry class, and possibly a flag telling which type. How can the subroutine determine which type of class the pointer points to? I would like to avoid using a case/if statement which duplicates large portions of the subroutine since this is not much different than just having separate subroutines. Something like this?? - void func1(CGenericUnit* pGenericUnit, int type) { if (type == TANK) { CTankUnit* pUnit; pUnit = (CGroundUnit*)pGenericUnit; } else if (type == INFANTRY) { CInfantryUnit* pUnit; pUnit = (CInfantryUnit*)pGenericUnit; } // now use pUnit freely except locality is broken pUnit->setLocation(location); // etc } thanks in advance for any help you are able to provide, steve coward
Shannon Barber
Shannon Barber
...using a dynamic_cast<>

Odds are good there''s BSA if you need a dynamic cast.

Magmai Kai Holmlor
- Not For Rent
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Void
Void
You need double dispatching. Look at Scott Meyer''s More Effective C++ or search www.cuj.com
Kylotan
Kylotan
As far as I can tell, this is a simple use of virtual functions:
  
class CGenericUnit
{
virtual setLocation(LocationType newloc);
};

class CGroundUnit : public CGenericUnit
{
virtual setLocation(LocationType newloc)
{ // CGroundUnit specific stuff }

};

class CGenericUnit : public CGenericUnit
{
virtual setLocation(LocationType newloc)
{ // CInfantryUnit specific stuff }

};

You can now just call pGenericUnit->setLocation() and it should work properly.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite ]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.