C++ Encapsulation


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:

Difference between encapsulation and abstraction

Encapsulation Abstraction
It is done at the implementation level. It is done at the design level.
It is used to protect the data from the outside world. It is used to hide the background details.
It is implemented using access modifier (public, private and protected) It is implemented using abstract class and interface.


Like it? Please Spread the word!