Data Encapsulation in C++

In this tutorial, we will explain what encapsulation is in C++ with the help of examples.

C++ is an object-oriented programming language and has support for various properties, with data encapsulation being one of them. If we check any programming textbook, we find encapsulation defined as wrapping up of data and information in a single unit. But what does this wrapping up mean? Let us consider an example.

Example

Suppose you have a bank account. If your bank details are made public, would you like it? Obviously no! You would never want your bank details to go public for security. For this reason, a bank account is made private and can be accessed only by you. This is data hiding or data encapsulation.
Similarly, in a class, we have private and public members. We can access public members anywhere outside the class but not the private members. The private members can only be accessed by members defined inside the class.

Thus encapsulation provides a protective mechanism that prevents any access to private members outside of its defined class.

C++ Data Encapsulation Code Example

#include<bits/stdc++.h>

using namespace std;
class encap {
  private:
    int x;
  public:
    void example(int y) {
      x = y;
    }
  int obtain() {
    return x;
  }
};

int main() {
  encap z;
  z.example(4);
  int ans = z.obtain();
  cout << ans;
  return 0;
}

 

Output:
4
  • In this example, we have defined a class named encap.
  • It takes a private member x of type int.
  • Public members contain two functions, example() and obtain().
  • example() assigns the value of x to some integer y.
  • obtain() will return the value of x.
  • In the main function, we have defined a class object z to access the members of the class.
  • example() is passed with the value 4. This function will then assign 4 to value of x.
  • obtain() would then return the value 4 and it is printed.
  • Thus, private members in the class can only be accessed by members inside the class. We cannot access them directly with a class object.
  • This is encapsulation, where security (or data is hidden) is provided to the private members of the class.

Leave a Reply

Your email address will not be published.