Now we're moving on to one of the real powerful aspect of classes: Inheritance. Inheritance lets you combine classes with similar code together, and it also lets you keep the unique properties
needed in each class.
For the first example, we're going to combine some similar aspects of the last lesson. Notice that every one of our classes shares a common theme. They all have X and Y coordinates of their
coordinates in the virtual world. We can create a class which has these coordinates and then create other classes which inherit from this base class.
class MapObject
{
protected:
int m_x;
int m_y;
public:
MapObject( )
{
m_x = 0;
m_y = 0;
}
void SetPosition( int x, int y )
{
m_x = x;
m_y = y;
}
void GetPosition( int *pX, int *pY )
{
*pX = m_x;
*pY = m_y;
}
};
Now we can have our other objects, inherit from this class.
class Person : public MapObject
{
protected:
char m_name[ 32 ];
public:
Person( )
{
m_name[ 0 ] = NULL;
}
void SetName( const char *pName )
{
strcpy( m_name, pName, sizeof(m_name) );
}
void GetName( char *pName, int length )
{
strcpy( pName, m_name, length );
}
void Speak( void )
{
printf( "The person is speaking!\n" );
}
};
With this method we can now use all of the functionality in MapObject within our Person class. If we were to use it inside a program it would look like this:
void main( void )
{
Person farmer;
farmer.SetName( "John" );
farmer.SetPosition( 10, 20 );
}
Notice we can use the position information which came with MapObject inside of the person class! Now we'll rework our other classes
so they also inherit from MapObject
class Animal : public MapObject
{
protected:
char m_name[ 32 ];
public:
Animal( )
{
m_name[ 0 ] = NULL;
}
void SetName( const char *pName )
{
strcpy( m_name, pName, sizeof(m_name) );
}
void GetName( char *pName, int length )
{
strcpy( pName, m_name, length );
}
void Speak( void )
{
printf( "The animal is speaking!\n" );
}
};
class Food : public MapObject
{
protected:
char m_type[ 32 ];
int m_amount;
public:
Animal( )
{
m_type[ 0 ] = NULL;
}
void SetAmount( int amount )
{
m_amount = amount;
}
void GetAmount( int *pAmount )
{
*pAmount = m_amount;
}
void SetType( const char *pType )
{
strcpy( m_type, pType, sizeof(m_type) );
}
void GetType( char *pType, int length )
{
strcpy( pType, m_type, length );
}
void Speak( void )
{
printf( "The %s is speaking!\n", m_type );
}
};
class Building : public MapObject
{
protected:
char m_color[ 32 ];
public:
Building( )
{
m_color[ 0 ] = NULL;
}
void SetColor( const char *pColor )
{
strcpy( m_color, pColor, sizeof(m_color) );
}
void GetColor( char *pColor, int length )
{
strcpy( pColor, m_color, length );
}
};