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.
We use the get
and set
methods to access an encapsulated (private attribute) class.
#include <iostream>using namespace std;// creating a classclass football_player { // this is the classprivate: // declaring a private memberint income; // This is the attributepublic:void setincome(int i) { // using the set methodincome = i;}int getincome() { // using the get methodreturn income;}};int main() {football_player myobject; // creating an objectmyobject.setincome(100000); // calling the methodcout << myobject.getincome(); // getting the attribute of the classreturn 0;}
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.
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.