Summary: In this tutorial, we will discuss Encapsulation in C++ with examples.

Encapsulation is one of the important properties of any object-oriented programming language.

Encapsulation in context of programming language is defined as wrapping up of data and functions into single unit (class).

When we create a class and declare variables and functions inside it, we are basically binding them together with the help of the class, thus implementing encapsulation.

With access specifier, we can also hide data outside the class, which is called Data Hiding.

Therefore we can say that encapsulation in a way implements abstraction.

Example of Encapsulation in C++

Output

Encapsulation in C++

In this program variable sum is private , therefore it cannot be accessed directly from main.

The getSum() method is used to access the value of sum.

By creating the class, we have bound sum and getSum() to work together, which is only possible through the object of the class.

In this tutorial, we learned what is encapsulation and what is its significance in C++.

Leave a Reply