C plus plus:Polymorphism

From GPWiki
Jump to: navigation, search

See Object_Oriented_Programming:Polymorphism

Example

// 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:
	std::cout << "Soldier: 'Ouch, taking damage!'\n";
}
// 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:
	std::cout << "Tank: 'Stop that!'\n";
}
// 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 CTank;
 
	// 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!'