Close
Close

Encapsulation in C++


Encapsulation is nothing new to what we have read. It is the method of combining the data and functions inside a class. Thus the data gets hidden from being accessed directly from outside the class. This is similar to a capsule where several medicines are kept inside the capsule thus hiding them from being directly consumed from outside. All the members of a class are private by default, thus preventing them from being accessed from outside the class.

Why Encapsulation


Encapsulation is necessary to keep the details about an object hidden from the users of that object. Details of an object are stored in its data members (member bables). This is the reason we make all the member variables of a class private and most of the member functions public. Member variables are made private so that these cannot be directly accessed from outside the class (to hide the details of any object of that class like how the data about the object is implemented) and so most member functions are made public to allow the users to access the data members through those functions.

For example, we operate a washing machine through its power button. We switch on the power button, the machine starts and when we switch it off, the machine stops. We don't know what mechanism is going on inside it. That is encapsulation.

Benefits of Encapsulation


There are various benefits of encapsulated classes.

  • Encapsulated classes reduce complexity.
  • Help protect our data. A client cannot change an Account's balance if we encapsulate it.
  • Encapsulated classes are easier to change. We can change the privacy of the data according to the requirement without changing the whole program by using access modifiers (public, private, protected). For example, if a data member is declared private and we wish to make it directly accessible from anywhere outside the class, we just need to replace the specifier private by public.

Let's see an example of Encapsulation.

#include <iostream>

using namespace std;

class Rectangle
{
	int length;
	int breadth;
	public:
		void setDimension(int l, int b)
		{
			length = l;
			breadth = b;
		}
		int getArea()
		{
			return length * breadth;
		}
};

int main()
{
	Rectangle rt;
	rt.setDimension(7, 4);
	cout << rt.getArea() << endl;
	return 0;
}
Output
28

The member variables length and breadth are encapsulated inside the class Rectangle. Since we declared these private, so these variables cannot be accessed directly from outside the class. Therefore , we used the functions 'setDimension' and 'getArea' to access them.

You know what you are but you don't know what you may be.

To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.
Ask Yours
Post Yours
Doubt? Ask question