Private? The false assurances of C++

Yet another reason I believe that C++ is the wrong language for teaching introductory programming. Because of the way classes are laid out in memory, it is trivial to show (a good thing), but it is also trivial to access those private member variables directly.

TLDR? – View the gist on github

Let’s break this down. We have a class called Point

point1

The point class in this instance represents a 2D and has the private member variables of x and y.

point2

If we have, say, a local variable (Point p;) we can do some basic calculations. This may be compiler / OS / architecture dependent, but this works in 32-bit linux w/ gcc on i386.

point3

When we run this code, we see that the sizeof(point) is identical to the sizeof(int) + sizeof(int). Since classes in C++ are based on structs in C. This is just a tight packing of the member variables.

And if the base pointer for &p is 0xa43c then we see that the address of x is the same, and y is off by 4 bytes (the size of an int).

Now – if we just try to access the private member variable directly, i.e. p.x = 27; the compiler will detect that we’re trying to do something bad and give us an error (good!).

However, through the magic of memory addresses and pointers we can change that. It is a simple cast. First we get a pointer to our instance of the Point class, and then we re-interpret that as a pointer to an int. From there we can start derferencing and using pointer math.

point4

That’s it. A simple cast and some pointer math and private doesn’t mean anything. Who needs encapsulation anyway?

One thought on “Private? The false assurances of C++

Comments are closed.