Data struc. and algo. with C++ class........
Solution:
In general terms, encapsulation is defined as wrapping up of information and data in a single unit.
For example, In an organization suppose three departments are there, IT, HR and sales, so here an employee within the department will have access to a certain amount of information based on the privilege which he/she got.
Suppose an employee from IT requires a piece of information about his/her details, then he/she will ask the HR about this (for example salary breakout for filing taxes and all).
code:
#include<iostream>
using namespace std;
class Enc
{
private:
//This data is set private so that
it is hidden
int data;
public:
//The method is set public so anyone can access it
void setData(int num)
{
data =num;
}
//This mehod is to return the value of data
int getData()
{
return
data;
}
};
// main method or driver program
int main()
{
Enc obj; //intantiating the object
obj.setData(5);
cout<<obj.getData();
return 0;
}
Output:
5
Explanation:
Since the variable data's access modifier is private, this means that only methods within the class can access it, which makes getData(), and setData, binded with x which is nothing but encapsulation.
code without encapsulation:
#include<iostream>
using namespace std;
class Enc
{
public:
//This data is set private so that
it is hidden
int data;
public:
//The method is set public so anyone can access it
void setData(int num)
{
data =num;
}
//This mehod is to return the value of data
int getData()
{
return
data;
}
};
// main method or driver program
int main()
{
Enc obj; //intantiating the object
obj.setData(5);
cout<<obj.getData();
return 0;
}
Hit the thumbs up if you liked the answer. :)
Get Answers For Free
Most questions answered within 1 hours.