Google

Concept of Data hiding in a class in C++

Written on:May 13, 2013
Comments are closed


Concept of Data hiding in a class in C++

In C++, the class groups data members and functions under three access specifiers – private, protected and public, where private and protected members remain hidden from outside world and thereby support data hiding, so that only relevant and required information is exposed to the user and rest of the unnecessary information remains hidden from the user.  The private and protected membes remain hidden from the user and the public members form an interface by providing the relevant and needed information to the outside world, which is nothing but data hiding.  Consider the following example:

class student
{
int roll_no;
public:
int rno;
void get_info()
{
roll_no = 5;
}
void put_info()
{
cout<<”Roll no = “<<roll_no;
}
};
void main(void)
{
student obj;
obj.roll_no = 5;  //results in an error //message-roll_no //not accessible.
obj.rno = 7;  // a valid assignment
obj.get_info();
}

In the above example, when the private variable roll_no is referred to by the object of the same class, it results in an error message, as a private member is accessible to only member functions.  So in order to initialize this private data member, a member function named get_info() is used, that assigns the value 5 to roll_no.  But the second assignment is perfectly a valid assignment in C++ as rno is a public variable.  Hence data members are hidden by specifying them under private section in a class.

 

Sorry, the comment form is closed at this time.