Reputation: 1494
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.
Upvotes: 2
Views: 153
Reputation: 126927
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.
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.Upvotes: 5