How the data is hidden & safe if encapsulation is implemented..explain with an example!!!
Answers
Answer:
The primary use for encapsulation is to hide implementation details from calling code. When calling code wants to retrieve a value, it should not depend on from wherethe value comes. Internally, the class can store the value in a field or retrieve it from some external resource (such as a file or a database).
Explanation:
please mark me as brainlist
Explanation:
:
Data Hiding in C++: What is Encapsulation and Abstraction?
Last updated on Nov 25,202022.8K Views
edureka
edureka
In simple words, data hiding is an object-oriented programming technique of hiding internal object details i.e. data members. Data hiding guarantees restricted data access to class members & maintain object integrity. In this blog, we will understand how data hiding works in C++. Following topics are covered in this tutorial:
Encapsulation
Abstraction
Data Hiding
Encapsulation, abstraction & data hiding is closely related to each other. When we talk about any C++ program, it consists of two fundamental elements:
Program statements – Part of the program (functions) that performs actions.
Program data – Data in the program which is manipulated using functions.
Encapsulation
Encapsulation binds the data & functions together which keeps both safe from outside interference. Data encapsulation led to data hiding.
Let’s look at an example of encapsulation. Here, we are specifying the getter & setter function to get & set the value of variable num without accessing it directly.
Example:
#include<iostream>
using namespace std;
class Encapsulation
{
private:
// data hidden from outside world
int num;
public:
// function to set value of
// variable x
void set(int a)
{
num =a;
}
// function to return value of
// variable x
int get()
{
return num;
}
};
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}