difference between encapsulation and data hiding

Can anybody tell me what is the difference between encapsulation and data hiding with example? dun need the bookish one.
Encapsulation means to protect sensitive information in an object by making members protected or private in a class. The user then has to use functions to change the state of the object, rather than [possibly incorrectly] modifying the object directly. This helps assure than an object is always "stable" and can't be corrupted. It also makes classes much harder to misuse and less likely to cause serious problems in a program.

Data hiding is an extreme version of encapsulation where you not only don't want the user to access the data members, but you also don't even want them to be able to see what they are. This is typically accomplished by using a void pointer or a forward declared struct pointer as the class data.

Here's an example of typical encapslation:

1
2
3
4
5
6
7
8
class MyClass
{
public:
  // members functions and stuff here
private:
  int foo;  // members are visible (not hidden)
  int bar;  //  but are still private (encapsulated)
};


Here's an example of data hiding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyClass
{
public:
  // member functions and stuff here
private:
  struct Data;
  Data* data;  // user cannot see what 'data' this class uses
        // therefore it's hidden
};

//================
//  then, in the .cpp file... the struct would need to be defined

struct MyClass::Data
{
  int foo;
  int bar;
};
Topic archived. No new replies allowed.