C++ | Encapsulation

Updated: Jun 11, 2020

Encapsulation may be a process of mixing data members and functions during a single unit called class. this is often to stop the access to the info directly, the access to them is provided through the functions of the category .

How Encapsulation is achieved during a class-

  • Make all the info members private.

  • Create public setter and getter functions for every data member in such how that the set function set the worth of knowledge member and get function get the worth of knowledge member.

Encapsulation Example in C++ :

using namespace std;
class Rectangle
	int length;
	int breadth;
		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;


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

Advantages of Encapsulation-

  • The key advantage of using an Object Oriented programming language like Java is that it provides your code - security, flexibility and its easy maintainability through encapsulation.

  • Encapsulation is additionally useful in hiding the data(instance variables) of a category from an illegal direct access.

  • Encapsulation also helps us to form a versatile code which is straightforward to vary and maintain.

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science

15 views1 comment

Recent Posts

See All

        Contact Us


  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door