Encapsulation is a technique through which, functions are provided (public) which operate on the hidden data (private) and return the results.
Internal data could be implemented in many ways(bcoz its hidden), without effecting the interface.
Does this mean, Encapsulation is same as data hiding ?
Using private or protected as encapsulation provides a protective shell but does not hide the implementation completely.
If you change the private implementation of your class, you still need to rebuild all the classes that use it, which is why people use “pImpl” and similar techniques to totally hide the implementation detail.
In C, there is no private or protected, but one will often create an implementation on forwardly-declared structs that the user never sees (e.g. FILE *) or even void * pointers that are often typedef’ed to some Handle type.
I will give a reference to
Herb Sutter’s blog about using pImpls.
I would generally say that using encapsulation via private/public is a weak form of abstraction, data hiding is a stronger form of abstraction (if abstraction is a good word for hiding the implementation detail) but terminology has always been one of my weaker points.
However even if you are going to use pImpl or whatever, you don’t want any class or whatever doing anything you like with your implementation detail. There are normally rules as to what can do what, and that is what the “encapsulation” model really brings.
Some people think that a friend breaks encapsulation but it can actually enhance it, for example, letting a factory object write to the private members of the class. The factory object is like the builder who is building your house, and you give them the access to put everything in its correct place for you.
And if you write unit tests (and you should) you can allow your unit tests access to the private members of your class too, to test that you got your implementation right.
So, encapsulation and data (implementation) hiding are both good things to have and should be used in the appropriate manner. They achieve similar things in assigning the roles but are not exactly the same.