Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps
both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
It is a method for protecting data from unwanted access or alteration by packaging it in an object where it is
only accessible through the object's interface. Encapsulation is often referred to as information hiding, which means the value
of a variable is accessible to the objects of class but they cannot
change the value assigned to the variable. If scope of a variable is defined as private then the same will also not be accessible to
all objects of a class.
But both are different. In fact information hiding is actually the result of Encapsulation. Encapsulation makes it possible to
separate an object's implementation from its original behavior - to restrict access of its internal data. This restriction facilitates
certain details of an object’s behavior to be hidden. This allows protecting an object's internal state from corruption by its user.
It is the mechanism by which Abstraction is implemented. In other words you can say that it is the result of the Encapsulation.
Example :- The Laptop is an object that encapsulates many technologies/hardware that might not be understood clearly by most people who use it.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied
that a class can contain private, protected and public members. By default, all items defined in a class are private.
Example :-
class Box { public: double getVolume(void) { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };
The variables length, breadth, and height are private. This means that they can be accessed only by other members of the Box class,
and not by any other part of your program. This is one way encapsulation is achieved.