C++ - Encapsulation
Access Specifier
Before understanding the concept of encapsulation, it is important to understand the concept of access specifier. Access specifiers defines the access type of the members and functions of the class and there are three types of access specifier in C++.
- public: members of the class are accessible from everywhere.
- protected: members of the class are accessible within the class and by friend and inherited classes.
- private: members of the class are accessible within the class and by friend classes.
Example:
In the example below, a class called Circle is created which has a private data member called radius. When it is accessed in the main() function, it raises an exception because it is a private member and it can not be accessed outside the class in which it is defined.
#include <iostream> using namespace std; class Circle { private: int radius = 10; }; int main () { Circle MyCircle; cout<<MyCircle.radius; return 0; }
The output of the above code will be:
error: 'int Circle::radius' is private within this context
Encapsulation
Encapsulation is a process of binding the data and functions together in a single unit called class. It is aimed to prevent the direct access of data members and available only through functions of the class. Data encapsulation led to the important concept of data hiding in object-oriented programming also known as Data abstraction. Data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.
Data Encapsulation steps:
- Declare each data members private
- Create public set function for each data members to set the values of data members
- Create public get function for each data members to get the values of data members
In the example below, public set and get functions are created to access private member radius of class Circle.
#include <iostream> using namespace std; class Circle { private: //data hidden from outside world int radius; public: //function to set the value of radius void setRadius(int x) { radius = x; } //function to get the value of radius int getRadius() { return radius; } }; int main (){ Circle MyCircle; //set the radius MyCircle.setRadius(50); //get the radius cout<<MyCircle.getRadius(); return 0; }
The output of the above code will be:
50