Sign in to follow this  

Question about using classes...

This topic is 4746 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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" ) ;


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4746 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this