Data Encapsulation in C++ || OOPs Concept || C++
In a Bank(class), there are different sections such as deposit section(data), withdraw section(data), enquiry section(data) and etc. The Deposit section handles all the deposits done by the account holders and keeps a record of them. In the same way, the Withdraw section also maintains all the records for all withdrawals done by the consumers(functions). So, if, someday a senior asks the Deposit section to show all the records of withdrawals done this month. In this case, he is not allowed to directly access the data of Withdraw Section. He will first have to contact some other officer in the Withdraw Section and then request him to give the particular data. This is what encapsulation is, here the data of Withdraw Section and the consumers(functions) that can manipulate them are wrapped under a single name “Withdraw Section”. This is what Data Encapsulation in real-life means. 



What is Data Encapsulation in C++?

-> Encapsulation is defined as wrapping up Data and other information in a single unit called a class. 
->It is a concept of OOPs which binds together the data and functions that can change the data, encapsulation helps to keep this data safe from the outside world and also prevents misuse of that data.
-> Data encapsulation led to the important OOP concept of data hiding.

In C++, the Data can be hidden by using two Access Specifiers given below,
1. private
2. protected
there's one more access specifier known as public this is not used to hide data in C++. For detailed information on all access specifiers click here

Example: 

#include <iostream>
using namespace std;

class Employee
{
    private:
    // Private attribute
    int salary;

    public:
    void setSalary(int s)
    {
        salary = s;
    }

    int getSalary()
    {
        return salary;
    }
};

int main()
{
    int a;
    Employee myObj;
    cout << "Enter Salary: ";
    cin >> a;
    myObj.setSalary(a);
    cout <<"The Salary is: "<< myObj.getSalary();
    return 0;
}
Output for example of Data Encapsulation:


#ENJOY CODING


Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post