C++ Encapsulation

The essential features of OOP are — encapsulation, inheritance and polymorphism.

Encapsulation is an important concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. It also leads to the OOP concept of data hiding and data abstraction.

Data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

To achieve data hiding, we must declare data members as private so that they cannot be accessed from outside the class. If we want users to modify or read the value of a private data member, we can provide public setter and getter member functions in class definition.

 

Data Encapsulation Example

Any program in C++ that implements a class with public and private members is an example of data encapsulation (data hiding and data abstraction also).

To access a private data member, we can use public setter and getter member functions. Consider the following example −

#include <iostream>
using namespace std;

class Circle {

private:
// data member : hidden from outside world
double radius;

public:
// setter member function : interface to outside world
void setRadius(double r) {
radius = r;
}

// getter member function : interface to outside world

double getRadius() {
return radius;
}
};

int main() {
// create object of Circle class
Circle cir;

// calling setter function using object
cir.setRadius(14);

// calling getter function using object
cout << "RADIUS: " << cir.getRadius();

return 0;
}

Output:

RADIUS: 14

NOTE: Any public member function in C++ will provide an interface to the outside world.

 

Explanation of the program:

The radius data member is private, which is basically hidden from the outside world (i.e. outside class).

The public setRadius() member function takes a parameter (r) and assigns it to the radius data member (radius = r).

The public getRadius() member function returns the value of the private radius member data.

Inside main() function, we create an object of the Circle class.

Now we can call the setRadius() function using the object to set the value of radius to 14.

Then we call the getRadius() function on the same object to return the value of radius.