Search code examples
c++processor

How the private and public variables in cpp are distinguished at machine level using the executable file?


we all have an idea about private and public variables in c++. Is there any mechanism to distinguish the private and public members at machine level ? If the data members are accessible by using the addresses of the members then why to use the private and public in c++ programming.


Solution

  • private and public in C++ are entirely compile-time concepts; they are not enforced in any way at runtime. Classes and their semantics are just blueprints to tell the compiler to lay data in memory in a certain manner; at runtime there's only bytes of data and code that accesses them with some given offsets.

    If the data members are accessible by using the addresses of the members then why to use the private and public in c++ programming.

    There are two big misconceptions here; first of all, they need to be accessible through address even "from the outside", otherwise a class couldn't provide to its clients references to its private fields (also, it's not clear how inlining would work).1

    But most importantly, C++ access control is not a security thing. The point of private and public is to establish a separation of interface and implementation detail (and thus helping the clients not to put the object in a logically inconsistent state, or relying on implementation details subject to change), not to make data unaccessible to untrusted code; code in your sources (or even just running in your process) is assumed not to be hostile.

    After all, if I really wanted to access private data of some library I could just edit the header and add a friend declaration, or do a #define private public, or (use some template trickery to access it legally.


    1. Notice that this is just the first and most obvious example that comes to mind. Even if you could devise a mechanism to track addresses obtained from "the inside" of the class (which would pose a lot of other problems with the semantics of pointers), the standard downright mandates that any T * can be safely casted to unsigned char * and read as an array of sizeof(T) unsigned char (see C++11 §1.7 ¶1, §3.9 ¶4, §3.10 ¶10), so that puts the nail in the coffin to this kind of protection mechanism.