Jach's personal blog

(Largely containing a mind-dump to myselves: past, present, and future)
Current favorite quote: "Supposedly smart people are weirdly ignorant of Bayes' Rule." William B Vogt, 2010

C++ supports encapsulation? Really?

No, it doesn't. For an excellent reference to make you cringe at the thought that C++ exists so abundantly, read the C++ FQA. Anyway, here's a trivial example of violating "private", which is just one way of showing that in C++ there's really no encapsulation at all.

#include <iostream>

using namespace std;

class Blah {
private: int n;

public: int k;

Blah() { n = 10; }

int main(int argc, char* argv[]) {
obj.k = 4;
cout << "k: " << obj.k << " size: " << sizeof(obj) << endl;
cout << "Hmm, where's that extra 8 bytes coming from? I bet it's " <<
"another int.\n";
//cout << obj.n; // compile error (hmm, no compile-time encapsulation..)
cout << "First four bytes are: " << *(int*)((char*)&obj) << endl;
cout << "Second four bytes are: " << *(int*)((char*)&obj + 4) << endl;
cout << "Which is k? Check: " << boolalpha <<
((int*)((char*)&obj + 4) == &(obj.k)) << endl;
cout << "Let's modify the private member!\n";
*(int*)((char*)&obj) = 7;
cout << "First four bytes are now: " << *(int*)((char*)&obj) << endl;

return 0;

Try it out. C++ sucks. (Tip: always cast to (char*) when doing pointer arithmetic, because then you're guaranteed to always be in terms of single bytes. (void*)'s size for arithmetic is undefined.)

Edit: I should mention that my favorite language Python doesn't support this type of encapsulation either, since even variables defined with a double underscore can still be accessed, but it doesn't pretend to and the practice isn't encouraged since you get better encapsulation in other ways. Any guide worth its salt will mention this, and you can always tell a Python n00b if they're using a bunch of getter and setter methods. Lastly, there is a lot more to OOP than just C++'s "structs with function pointers that are called automatically and have implicit arguments": a sign that you really just want a struct with a few helper functions is if you have many getter/setter methods. On this I have already written.

Posted on 2010-10-08 by Jach

Tags: c++, programming


Trackback URL:

Back to the top

Back to the first comment

Comment using the form below

(Only if you want to be notified of further responses, never displayed.)

Your Comment:

LaTeX allowed in comments, use $$\$\$...\$\$$$ to wrap inline and $$[math]...[/math]$$ to wrap blocks.