c++ array with different classes (which extend a base class)

Member
Posts: 749
Joined: 2003.01
Post: #1
In C++, suppose I have wrote a "Ship" class with a "Handle" method, and then a "Ship1" and a "Ship2" classes that extend Ship and have their own Handle method that overrides that of their superclass.

How do I go about making a ships array (or vector) with a Ship1 instance and a Ship2 instance and have them "handled" according to their proper "Handle" method (not that of the superclass)?

(I'd like to do

for(i=0;i<2;i++)
{
ships[i].handle()
}

©h€ck øut µy stuƒƒ åt ragdollsoft.com
New game in development Rubber Ninjas - Mac Games Downloads
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #2
Just have the array hold pointers of type "Ship".

Code:
std::vector< Ship * > ships;
ships.push_back( new Ship1(...));
ships.push_back( new Ship2(...));

for ( int i = 0; i < int( ships.size()); i++ ) ships[i]->Handle();

One thing to keep in mind is that the Handle class declared in the Ship baseclass has to be virtual.

Code:
class Ship
{
   Ship( void ){}
   virtual ~Ship( void ){}

   virtual void Handle( void ) { default handle code; };
}

You could also define Ship::Handle as pure virtrual if that float your boat:
Code:
virtual void Handle( void ) = 0;

This will force the compiler to only allow instantiations of classes derived from Ship which override Handle().
Quote this message in a reply
Member
Posts: 749
Joined: 2003.01
Post: #3
Thanks... so basically you're forced to use heap memory for the ships?

©h€ck øut µy stuƒƒ åt ragdollsoft.com
New game in development Rubber Ninjas - Mac Games Downloads
Quote this message in a reply
Oldtimer
Posts: 834
Joined: 2002.09
Post: #4
Yes, because the compiler can't create arrays where the elements might be of differing sizes.
Quote this message in a reply
Member
Posts: 749
Joined: 2003.01
Post: #5
Right, that makes sense... Finally a good reason to use "new" Smile

©h€ck øut µy stuƒƒ åt ragdollsoft.com
New game in development Rubber Ninjas - Mac Games Downloads
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Adding Member Variables to Classes FlamingHairball 2 3,159 Jan 12, 2008 02:43 PM
Last Post: FlamingHairball
  Classes in Interface Builder FlamingHairball 6 3,915 Jan 9, 2008 03:01 PM
Last Post: FlamingHairball