Web Tutor

Other Entries

C++ Data Encapsulation

Encapsulation is one of the key features of object oriented programming. It involves the building of data members and functions inside a class.
Building similar data members and functions inside a class also helps in data hiding. 
In general, encapsulation is a process of wrapping similar code in one place. 
In C++, we can bundle data members and functions that operates together inside a class. For example:
class Rectangle{
       public:
            int length;
            int breadth;

       int getArea()
         {
           return length * breadth;
         }
};

 

In the above program, the function getArea() calculates the area of a rectangle. To calculate the area, it needs length and breadth. 

Hence the data members length and breadth and the function getArea() are kept together in the rectangle class. 

 

Example

#include <iostream>
#include <math.h>
using namespace std;

class Rectangle{
       public:
           //Variables required for area calculation
        int length;
        int breadth;

        //Constructor to initialize variable
        Rectangle(int len, int brth): length(len), breadth(brth) {}

       int getArea()
         {
           return length * breadth;
         }
};
int main()
{
    //Create object of the Rectangle class
    Rectangle rect(8,6);

    //Call getArea() function
    cout<<"Area = "<<rect.getArea()<<endl;
    return 0;
}

 

Output

450_fc3f5842f60089752efe1845a28e07a1.png

In the example above, we are calculating the area of a rectangle. 

To calculate an area, we need two variables: length and breadth and a function: getArea(). Hence we bundled these variables and function inside a class called Rectangle. 

The variables and functions can be accessed from other classes, hence this is not data hiding. This is encapsulation, we are just keeping similar codes together. 

The importance of Encapsulation

  • It helps control the modification of our data members. 
  • The getter and setter functions provide read-only or write-only access to our class members. 
  • It helps to decouple components of a system. For example, we can encapsulate code into multiple bundles.
  • We can also achieve data hiding using encapsulation. For example in the above code, if we change the length and breadth variables into private and protected, then the access to these field are restricted.
Posted in C++ on November 10 2022 at 02:58 PM

Comments (0)

No login