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:
roll_no = 5;
cout<<”Roll no = “<<roll_no;
obj.roll_no = 5; //results in an error //message-roll_no //not accessible.
obj.rno = 7; // a valid assignment
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.