You are here:

C++/Is data hiding can be done in c++

Advertisement


Question
when i first learned C++ i learned the Concept of data hiding,By declaring the variables/methods as private/protected But even though they are declared private /protected we can access the data outside the class. Here is a sample code.

class sample
{
private:
     int var;
public:
     sample()
     {
       var = 20;
     }
    void display()
    {
      cout<<var;
    }
};

main()
{
 sample *pSample = new sample;
 pSample->display();
 int *ip = (int *)psample;
 *ip = 40;
 pSample->display();
 return 0;
}
 

by seeing this can you justify where is data hiding?

 why people are saying that data hiding is done in C++? How is it possible.


Answer
Hi,
 This way not only you can see but also write the data using memcpy() :--).
Data hiding is not at the binary level. It is till the C++ level where using C++ you would not be able to change the data. Yeah of course if you use this kind of stuff, not always you would be able to get what you want.
For example, if you have more than 1 variable as private, you would find it very difficult to read/change the values as they are re-arranged by the compiler, padded etc.

Thanks,
RaiD

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Dharmender Rai

Expertise

I can answer general and system level C/C++ questions.

Experience

I have 5 years of experience in C++.

©2016 About.com. All rights reserved.