Breaking Information Hiding in C++

Almost every object-oriented programmer is familiar with the concept of information hiding. Actually, lots of them get confused with the terms encapsulation and information hiding. So, before we talk about information hiding itself, let me explain the difference of both terms:

  • Encapsulation is the public interface that defines how an object can be used, and how its data is derived.
  • Information Hiding is the principle of hiding design decisions, preventing external objects from using the derived data.

Now let’s take a look in a real sample. The code below shows a classic header file, corresponding to a Point class. Note that class’ members are protected against modification, since they are declared as private and no setter methods were provided. The class data is also encapsulated into the Point interface, which defines how Point objects are used, through its constructor and getter methods.



A very common issue when using a third-party API is the need of changing private members value when running some tests. However, if no setter methods exist, the change can’t be made, right? Well, in C++ things are pretty different. When using pointers, you’re working directly with memory addresses. So if we create pointers that make reference to private member’s address, we can manipulate its value. Look at the code below.



Note that I’m using an integer pointer, which is an array of integers. If we come back to Point class definition, we will see just two integers. Therefore, in respect with memory manipulation Point class is similar to an integer array. In other words, array[0] is the same of point->x since both read int values (4 bytes in win32 platform). When doing the pointer attribution and the explicit cast, we’re just pointing the integer array to the first memory address of the object. Changing its value will affect the memory content, it means: the object private member.

I know that this is a little bit weird, but it works perfectly. To looks like more acceptable, we could create a new class, similar to Point class signature, and manipulate its members, but in fact working with the Point class member variables. Here is the code that illustrates this behavior.





Now, be free to change private members wherever you want.

See you,



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s