What is encapsulation in C++?

Overview

Encapsulation in C++ is a term that is used to describe a situation where specific data (sensitive, as the case may be) is being hidden from users. A class attribute must be declared private, so that it can only be accessed inside a given class. 

To better understand the concept of access specifiers in C++, we may refer to this linked shot.

How to create and access the attributes of an encapsulated class

We use the get and set methods to access an encapsulated (private attribute) class.

Code example

#include <iostream>
using namespace std;
// creating a class
class football_player { // this is the class
private: // declaring a private member
int income; // This is the attribute
public:
void setincome(int i) { // using the set method
income = i;
}
int getincome() { // using the get method
return income;
}
};
int main() {
football_player myobject; // creating an object
myobject.setincome(100000); // calling the method
cout << myobject.getincome(); // getting the attribute of the class
return 0;
}

Code explanation

  • Line 5: We create a class called football_player.

  • Line 6: We declare a private member or attribute of the class using the private keyword.

  • Line 7: We create an attribute of the class, income.

  • Line 10: We set the attribute of the class income as an integer type using the set method.

  • Line 13: We return the value of the attribute income whenever the function is being called using the get method.

  • Line 19: We create an object of the class myobject.

  • Line 20: We call the method to set the value of the income attribute of the function.

  • Line 21: We call the method to return the value of the set value of the income attribute of the class.

Why is encapsulation important?

  • Encapsulation gives a user better control over data. In essence, encapsulation ensures that a user can always change a part of the code without affecting the rest of it.

  • Encapsulation helps to improve the security of the data.

Free Resources