This is the final post in the series of the three cornerstones of object oriented programming. Next week I’m going back to a nice low-level subject – the bitwise operators :-).
So. What is encapsulation?
I previously defined this as the ability of objects* to maintain their internal workings independently from the program they are used in.
This is actually the simplest of the three concepts we’ve covered. With respect to C++, encapsulation describes the use of a class to contain both its relevant data, and the methods to manipulate its own data.
As a simple example, you might define a class called Message. This class can contain various data members, such as the sender’s address, the date the message was written, the destination address, and of course, the actual message inside.
The class can also contain methods to manipulate a Message object. For example it might have a method to set the object status to ‘read’, and another method to print the message to the screen.
The fact that the Message class both contains its own data, and provides a way to interact with that data, is what encapsulation is all about.
It’s such a fundamental part of C++ (and other OO languages), that it is often taken for granted.
Why is this a good thing?
The benefits of encapsulation are:
- It can restrict access to an object’s data.
If data is declared as private and methods are generated to access that data, it can provide a good level of control over the data and how it is used.
- It allows the programmer to modify the object under-the-hood without disrupting the rest of the program.
If you want to change the internals of your class, you can do so without having to modify code elsewhere in the program, as long as you keep the methods to access that class the same.
Encapsulation is the class not the object
Note that encapsulation is provided by the class, not the instantiated object (there is a subtle difference). This is because a class can provide the ability to access information about every object that is instantiated from it, whereas a single object is just that.
And that wraps up our mini-guide to OOP. Hope it was useful, and don’t forget to pop back soon for some fun with bitwise operators.
*In C++ note that is it officially the class that is the unit of encapsulation, not the individual object itself.