WHAT IS ENCAPSULATION?
- In C++, the encapsulation is a process of combining data members and functions in a single unit known as class.
- This is to prevent the access to the data directly and the access to them is provided through the function of the class. It is one of the most important features of object oriented programming that helps in data hiding.
- The data encapsulation is a mechanism packing the data and the functions that use them in a single unit and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
- The C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes.
HOW TO ACHIEVE ENCAPSULATION?
We can achieve the encapsulation in two ways:
- Create set and get functions as public for each data member in such a way that the set function set the value for the data member and get function get the value for the data member.
- Making the entire data members private.
ADVANTAGES OF ENCAPSULATION
Some of the advantages of encapsulation are:
- It helps to protect the data as the person cannot change the data if it is encapsulated.
- You can change the privacy of the data according to the requirement without changing the whole program by using the access modifiers.
- Encapsulated class reduces the complexity.
LET US HAVE A LOOK AT THE EXAMPLE TO BETTER UNDERSTAND IT: