Google News
logo
CPP - Interview Questions
Define Encapsulation in C++?
Encapsulation is the process of binding together the data and functions in a class. It is applied to prevent direct access to the data for security reasons. The functions of a class are applied for this purpose. For example, the customers' net banking facility allows only the authorized person with the required login id and password to get access. That is too only for his/her part of the information in the bank data source.

In C++ encapsulation can be implemented using Class and access modifiers. Look at the below program :
#include <iostream>
using namespace std;

class Encapsulation
{
	private:
		// data hidden from outside world
		int x;
		
	public:
		// function to set value of
		// variable x
		void set(int a)
		{
			x =a;
		}
		
		// function to return value of
		// variable x
		int get()
		{
			return x;
		}
};

// main function
int main()
{
	Encapsulation obj;
	
	obj.set(5);
	
	cout<<obj.get();
	return 0;
}


Output : 5

Advertisement