Table of Contents
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.
Benefits of encapsulation
Access Specifier
There are three types of access specifier
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
Multiply two numbers in Java using scanner| 5 different ways In this article, we will…
5 Different ways to Divide two numbers in Java using scanner In this article, we…
Learn 8 Ways to Subtract Two Numbers Using Methods in Java In this article, we…
10 ways to subtract two numbers in Java In this article, we will discuss the…
Java Code Examples – Multiply Two Numbers in 5 Easy Ways In this article, we…
How to Divide two numbers in Java| 5 different ways In this article, we will…
This website uses cookies.