Encapsulation is a concept where you have a complex object which manages itself automatically. The user of an encapsulated object does not need to worry or care
how the object actually works internally. And in fact, the less the user knows about it, the better the encapsulation is.
Classes are a tool which can be used to easily implement the concept of encapsulation.
Encapsulation is considered a good thing because it keeps areas of code isolated, which makes them easier to maintain, easier to debug, and easier to use. It also allows you to change the implementation (how the class actually works under the hood) without breaking any other code.
An example of a class which is encapsulated is std::string:
1 2 3 4 5 6 7 8 9
|
#include <string>
int main()
{
std::string obj = "This is an encapsulated string.";
obj += " You can resize the string effortlessly.";
obj += " All the work being done is hidden from you, the user."
obj += " Memory management, etc, is all hidden, so it's difficult to misuse the class."
}
|
Internally, what std::string does is quite complex. It does all sorts of buffer allocation and management. However it hides those details from you, so you can use it very easily and naturally. That's what encapsulation does.