C++ and object-oriented programming: encapsulation

Encapsulation is a well known term for software developers, but there is an important bit that is often ignored. Encapsulation hide some variables and methods in two ways, depending on the language. It is done on object or class level.

Encapsulation on object level prevent from using private methods and variables of one object in another object. This approach presents in Java.

Class level mean that the private members can not be accessed from objects of others classes. However, if there are two objects of the same class, they can access their private members each other. In this way encapsulation works in C++.

Example:
[code lang="c++"]
#include
#include
//
using namespace std;
//
class person {
private:
string secret_value;
public:
person( string item ):secret_value(item) { }
void steal( person &victim)
{
cout < < "steal: " << victim.secret_value << "\n";
}
};
//
int main()
{
person men("wallet"), thief("nothing special");
cout << "Thief try to get secret value.\n";
thief.steal( men );
return 0; //that program compiles and works
}
[/code]

Of course I have assumed in above descriptions that there were not any “friends”. A friend of an object can always use its private members.

That was my first article (and hopefully not last) on c++/object-oriented programming/design patterns. I hope you learn something new.

Leave a Comment

authimage