C++ - Encapsulation


Advertisements

Previous Page Next Page

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 are accessible from outside the class.
  • protected: members are not accessible from outside the class but accessible in friend and inherited classes.
  • private: members are not accessible from outside the class but accessible in friend classes.

Example:

In the below example, 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 of access specifier.

#include <iostream>
using namespace std;
 
class Circle
 {
   private:
     int radius = 10;
 };

int main (){
    Circle MyCircle;
    cout<<MyCircle.radius; 
    return 0;
}

Output

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 below example, public set and get function is created to access private member radius of class Circle.

#include <iostream>
using namespace std;
 
class Circle
 {
   private:
     int radius;

   public:
   void setRadius(int x)
   {
    radius = x;
   }
   int getRadius()
   {
    return radius;
   }
 };

int main (){
    Circle MyCircle;
    MyCircle.setRadius(50);
    cout<<MyCircle.getRadius(); 
    return 0;
}

Output

50

Previous Page Next Page