C++ Encapsulation2 min read

Encapsulation is defined as the wrapping up of data(variable) under a single unit. Encapsulation is an important concept of OOP in C++ that binds data and functions inside a class together that manipulate them. Data encapsulation leads to the important concept called data hiding.

It makes sure that the ‘sensitive’ data are hidden from the user and an access specifier is used to achieve this. private specifier is used to hide sensitive data, it makes the data inaccessible from outside the class. But to modify or read those data, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.

Example of specifiers to bind data:

Let us go through an example in C++ to understand the concept of hiding data.


Data Hiding Using the private Specifier in C++

Output:

In the above program length and breadth in Rectangle class is a private member which means they are not accessible from outside the class. So to get and set the value of length and breadth, we created a setter (pass the value) and getter (return the value). Hence the private members are not accessible directly, making it hidden.


Benefits of Encapsulation:

  • Data- hiding in Java.
  • The class field can be made read-only or write-only.
  • It provides the class the total control over the data.

MORE

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More

Keith Number Program in C++

In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you …
Read More

Singly linked list Program C++

In this tutorial, we will write a C++ program to implement singly linked list. In this program, we will create a separate function for each …
Read More

Fascinating Number Program in C

In this tutorial, we will write a C program to check whether the given number is a Fascinating number or not. You may go through …
Read More

Peterson Number in C

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in C. What is Peterson Number? …
Read More

Peterson Number in C++

In this tutorial, we will learn about the Peterson number and write a C++ program to check if the given number is a Peterson number …
Read More