What is encapsulation? What are its advantages? How can encapsulation be enforced in C++?

The wrapping up of data members and member functions into a single unit is called encapsulation. The data members then can only be accessed by the member functions with which they have been tied up and not by the outside world. Encapsulation creates an interface between the object’s data and the program. A common use of information hiding is to hide the physical storage layout for data so that if it is changed, the change is restricted to a small subset of the total program. Encapsulation can be enforced in C++ using the concept of classes which binds data and function together. Through encapsulation, we can provide security to our data function. Private data and member functions will not be visible to outside world. 

For example, in the following class two members x, y declared as private can be accessed only by the member functions, not even in main( ) we can call these data members.

Lets understand the concept with an example:
Program Code:
#include<iostream>
using namespace std;
class A // declaration of class A
{
int a;
public:
// declaration and definition of member function getdata() of A
void getdata() 
cout<< “Enter value of a : ”;
cin>>a;
cout<<endl;
}
// declaration and definition of member function display() of A
void display() 
cout<< “The entered value value of a : ”;
cout<<a;
}
};
// declaration of main() function which is used to create class object and class member functions call
int main()
// object declaration of class A
A obj; 
// function call to getdata() with class object and dot (.) operator
obj.getdata();
// function call to display() with class object and dot (.) operator
obj.display();
return 0;
}



The program code is tested on www.jdoodle.com
Output:
Enter value of a : 7
The entered value value of a : 7


Thanks
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: