Table of Contents
Encapsulation in C++ programming language
In this tutorial, we will discuss the OOP concept of Encapsulation in C++ programming language
Encapsulation is the process to enclose data members and methods in a single unit for security purposes. This is also known as data abstraction. This is possible in Oop languages like C++ and Java. That means encapsulation is the method of combining data and function inside a class. This process helps to hide the data from being accessed from outside of a class directly. Only through the functions inside the class, access to information is available.
- Data encapsulation is a mechanism used to bundle data and the function.
- Encapsulation is used for data hiding. Data hiding is a mechanism where the details of the class are hidden from the user.
- The user can perform only a set of operations in the hidden member of the class.
- Encapsulation is a powerful feature(in OOP concept) that leads to information hiding for security purposes.
Benefits of encapsulation
- Data hiding – Restriction of external access to the features of a class.
- Information hiding – The implementation details are not known to the user.
- Implementation independence – A change in the implementation is done easily without affecting the user interface.
Access Specifier
There are three types of access specifier
- private
- public
- protected
Encapsulation
In the above example, variables declared as private(x,y and z are private). This means that they can be accessed only inside the addition class. The private variable can not access other parts of your program or outside of your class.
The only way to access it is by creating a object of class addition;
This is one of the ways to achieve the encapsulation
Example 2
This is an example for encapsulation with passing arguments
Program 3
#include <iostream> #include <conio.h> using namespace std; class Rectangle{ private: int length;//private variables private: int breadth; public: void set_Area(int l,int b)//setter method { length=l; breadth=b; } int get_Area(){//getter method return length*breadth; } }; int main() { Rectangle R;//create object R.set_Area(9,5); //Call the method with argument cout << "The area of rectangle is: "<<R.get_Area() << endl; getch(); return 0; }
The above code is executed, it produces the following result
The area of rectangle is: 45
Abstraction in C++ Abstraction in Java
Encapsulation in C++ Encapsulation in Java
Polymorphism in C++ Methodoverriding in Java