Object Oriented Programming:Encapsulation
From GPWiki
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. [edit] EncapsulationEncapsulation (or "information hiding") is the process of hiding the data structures of the class and allowing changes in the data through a public interface where the incoming values are checked for validity. [edit] Example in C++// An example unit class class CUnit { private: int m_iHealth; public: CUnit(); virtual ~CUnit(); void SetHealth( int iHealth ); int GetHealth(); }; CUnit::CUnit() { // Set the health variable to the its default value m_iHealth = 100; } CUnit::~CUnit() { // The class is unloading } void CUnit::SetHealth( int iHealth ) { // Here we use the new health value that has been provided // but we make sure that the value is valid, and we have // the oppotunity to handle the situation where an invalid // value has been passed. // If the health is below zero if ( iHealth < 0 ) { m_iHealth = 0; // Trigger a function to kill the unit } // If the health is above 100 else if ( iHealth > 100 ) { m_iHealth = 100; // The player is cheating, ban their game account! } // The passed health value is between 1 and 100 and is valid else { m_iHealth = iHealth; } } int CUnit::GetHealth() { // Returns the value of the health variable return m_iHealth; } [edit] External Resources |


