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 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;}
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
privatekeyword.Line 7: We create an attribute of the class,
income.Line 10: We set the attribute of the class
incomeas an integer type using thesetmethod.Line 13: We return the value of the attribute
incomewhenever the function is being called using thegetmethod.Line 19: We create an object of the class
myobject.Line 20: We call the method to set the value of the
incomeattribute of the function.Line 21: We call the method to return the value of the set value of the
incomeattribute 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.