# 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:
public:
void setValues(int l, int b,int h) {
length = l;
height = h;
}
void calcVolume() {
cout<<"Length = " << length << endl;
};
Encapsulation obj;
obj.calcVolume();