Encapsulation in C++

C++ProgrammingServer Side Programming

Encapsulation brings together the data and the methods that manipulate the data into a single component and protects them from outside interference. In essence, encapsulation involves bundling the data as well as the functions that use the data. Data encapsulation in lead to the very important concept of data hiding.

Encapsulation in C++ is implemented using classes that are user defined data types. These classes contain data types as well as methods that are bound together.

A program that represents encapsulation in C++ using classes is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class EncapsulationDemo {
   private:
   int length, breath, height;
   public:
   void setValues(int l, int b,int h) {
      length = l;
      breath = b;
      height = h;
   }
   void calcVolume() {
      cout<<"Length = " << length << endl;
      cout<<"Breath = " << breath << endl;
      cout<<"Height = " << height << endl;
      cout<<"Volume = " << length*breath*height << endl;
   }
};
int main() {
   EncapsulationDemo obj;
   obj.setValues(5, 3, 2);
   obj.calcVolume();
   return 0;
}

Output

Length = 5
Breath = 3
Height = 2
Volume = 30

In the above program, the variables and methods are wrapped in a single unit i.e the class Encapsulation. So, this program demonstrates the concept of encapsulation.

The length, breadth and height in class Encapsulation are private variables. There are public functions that initialize these variables and also calculate the volume by multiplying length, breadth and height. The code snippet for this is as follows.

class Encapsulation {
   private:
   int length, breadth, height;
   public:
   void setValues(int l, int b,int h) {
      length = l;
      breadth = b;
      height = h;
   }
   void calcVolume() {
      cout<<"Length = " << length << endl;
      cout<<"Breadth = " << breadth << endl;
      cout<<"Height = " << height << endl;
      cout<<"Volume = " << length*breadth*height << endl;
   }
};

In the function main(), first an object of type Encapsulation is defined. Then the function setValues() is called with the values 5, 3 and 2. Finally, these values and the volume are displayed using the function calcVolume(). The code snippet for this is as follows.

Encapsulation obj;
obj.setValues(5, 3, 2);
obj.calcVolume();
raja
Published on 09-Oct-2018 06:19:20
Advertisements