Object Oriented Programming:Polymorphism

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

Polymorphism

Polymorphism is the idea that different classes can have different implementation of the same function.

Example in C++

// IBaseUnit is a pure virtual class, also known as an interface.
// You can not create instances of this class by itself
// as the functions is not implemented but only declared.
class IBaseUnit
{
public:
	// Declare a pure virtual function
	virtual void VTakeDamage( int iDamage ) = 0;
};
// A class that implements the IBaseUnit interface
class CSoldier: public IBaseUnit
{
public:
	// We declare the inherited virtual function
	virtual void VTakeDamage( int iDamage );
};
 
// Implementation of the virtual function
void CSoldier::VTakeDamage( int iDamage )
{
	// Handle what happens when the soldier takes damage
 
	// An audio clip with a scream could be played
	// A spray of blood and gore could be added
	// The soldier could fall to the ground if dead 
 
	// For now the function just have the following output:
	fprint( "Soldier: 'Ouch, taking damage!'" );
}
// A class that implements the IBaseUnit interface
class CTank: public IBaseUnit
{
public:
	// We declare the inherited virtual function
	virtual void VTakeDamage( int iDamage );
};
 
// Implementation of the virtual function
void CTank::VTakeDamage( int iDamage )
{
	// Handle what happens when the tank takes damage
 
	// An audio clip with a bullet impact sound could be played
	// A small explosion could be triggered
	// The tank could fall apart if too damaged 
 
	// For now the function just have the following output:
	fprint( "Tank: 'Stop that!'" );
}
// A class to show an example usage of polymorphism
class CGame
{
public:
	// Fake game function
	void DoGame();
};
 
void CGame:DoGame()
{
	// Here we make a pointer variable. It doesn't point to anything yet.
	IBaseUnit* pSomeUnit = 0;
	
	// Create a new object of type CSoldier
	CSoldier* pSoldier = new CSoldier;
	
	// Create a new object of type CTank
	CTank* pTank = new pTank;
 
	// Set pSomeUnit to point to the soldier object.
	pSomeUnit = pSoldier;
	// The soldier takes 10 points of damage
	pSomeUnit->VTakeDamage( 10 );
	
	// Set pSomeUnit to point to the tank object.
	pSomeUnit = pTank;
	// The tank takes 10 points of damage
	pSomeUnit->VTakeDamage( 10 );
 
	// Set pSomeUnit to point to the soldier object.
	pSomeUnit = pSoldier;
	// The soldier takes 5 points of damage
	pSomeUnit->VTakeDamage( 5 );
 
	// Always remember to clean up after yourself
	delete pTank;
	delete pSoldier;
}


Output:

Soldier: 'Ouch, taking damage!'
Tank: 'Stop that!'
Soldier: 'Ouch, taking damage!'

External Resources