Question about using classes...

Started by
4 comments, last by Raisor 19 years, 4 months ago
Lets say I have a basic Item Class such as this:
class Item
{
    public:
        int x,y;
}
and then I have two other classes that are derived from that class:
class Weapon : public Item
{
    public:
        int type;
        char name;
}

class Armor : public Item
{
    public:
        int type;
        char name;
}
Then I go and create an array to store the inventory of the characters like this:
Item inventory[10];

Armor breastplate;

inventory[1] = breastplate;
but that give me an error of unable to convert Armor to Item. Any ideas what I am doing wrong? I have even tried using this:
inventory[1] = (Item)breastplate;
but that does not work either. Any help would be appreciated.
Thanks,Tom Sapphttp://www.sappsworld.com
Advertisement
the array needs to be created like this:

Item* inventory[10];

look up pointers
t3h s0uRc3 c0dE sP33ks f0r 1ts3lth[itsealth]

   class IBase   {   protected :	   int x, y ;	   unsigned int type ;	   char* name ;   public :	   IBase() { }	   virtual ~IBase() { }	   virtual void SetPosition( int p_X, int p_Y ) = 0 ;	   virtual void SetType( unsigned int p_Type ) = 0;	   virtual void SetName( char* p_Name ) = 0 ;   } ;   class CWeapon : public IBase   {   public :	   CWeapon() { }	   virtual ~CWeapon() { }	   virtual void SetPosition( int p_X, int p_Y )	   {		   x = p_X ;		   y = p_Y ;	   }	   virtual void SetType( unsigned int p_Type )	   {		   type = p_Type ;	   }	   virtual void SetName( char* p_Name )	   {		   name = p_Name ;	   }   } ;   IBase * Gun = new CWeapon ;   Gun->SetPosition( 0, 0 ) ;   Gun->SetType( 1 ) ;   Gun->SetName( "Magnum" ) ;
---http://www.michaelbolton.comI constantly dream about Michael Bolton.
In order for the child classes to have access to the variables in the parent class those variables must be 'protected'. And as the above poster said it should be an array of pointers. I highly suggest looking up pointers, arrays, and polymorphism.
---http://www.michaelbolton.comI constantly dream about Michael Bolton.
And STL vectors.
Thank you both for your quick replies. I believe I understand what I did wrong and will go do the research suggested.
Thanks,Tom Sapphttp://www.sappsworld.com

This topic is closed to new replies.

Advertisement