OldSchoolCode

.com



Classes Part 4
Building on the inheritance we learned from the last lesson, we're going to introduce virtual functions. Virtual functions can be absolutely awesome when used correctly. They can keep your code size down and easier to read. However the over use of virtual functions can turn your code into a hard to debug disaster. The more you work with them, the more you'll learn to keep just the right balance.

virtual is the keyword we are focusing on here. It allows a function defined in your base class to be also defined in your derrived class. The derrived classes version will always override the base class version.

Consider our animal class. It's a great little class, but it isn't very specific to different animal types. When we call Speak, it won't make different animal sounds like "quack" or "bark". But we can change all that with derrived classes and virtual functions!
   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 );      
      }
      
      virtual void Speak( void )
      {
         printf( "The animal is speaking!\n" );
      }
   };
Notice the only thing we changed was to add the 'virtual' keyword with the Speak function. Now we can have specific animals types derrive from this class and have their own Speak function.
   class Duck : public Animal
   {
      virtual void Speak( void )
      {
         printf( "Quack!\n" );
      }
   };
   
   class Dog : public Animal
   {
      virtual void Speak( void )
      {
         printf( "Bark!\n" );
      }
   };

   class Pig : public Animal
   {
   };
See the beauty of this? Duck, Dog and Pig all have the properties of Animal and MapObject, plus Duck and Dog have their own Speak function. If they did not have a speak function (like Pig) then it would fall back on the Speak function in the Animal class.
void main( void )
{
   Duck duck;
   Dog dog;
   Pig pig;

   duck.SetName( "Donald" );
   duck.SetPosition( 10, 20 );
   duck.Speak( );

   dog.SetName( "Pluto" );
   dog.SetPosition( 20, 20 );
   dog.Speak( );

   pig.SetName( "Porky" );
   pig.SetPosition( 30, 30 );
   pig.Speak( );
}
Your output should look like:
   Quack!
   Bark!
   The animal is speaking!