Re: Memory Layout - Private , Protected and Public member
kanze wrote:
Jiang wrote:
bestbrain@gmail.com wrote:
Sujay,
1. With the kind of pointer power in C++, it is difficult to prevent
developer from accessing sub-parts of object. It may be difficult but
is it impossible?
In my mind this is not possible if we stay with the current
C++ object model. With a raw pointer in hand, you can do
whatever you want.
Even allowing for this, I'm not sure that an implementation
would be allowed to check access completely. I think that
you're allowed to do read an object byte by byte, including any
hidden and private parts; i.e. a hex dump of the object is legal
C++.
Yes, that's the point.
For a carefully designed class:
class my_great_class
{
// public interfaces
int private_state;
};
One can easily do
int *p = reinterpret_cast<int*>(&obj);
*p = 0xDEADBEEF;
to make something happen.
2. If it is possible to implement, why does not C++ add
runtime infrastructure to prevent access to private members?
I guess, any such checks will impact performance. But there
may be some developers who will accept slower speed for
safer application. How about adding keyword like
As I said, this kind of checking is not feasible and it won't
help at all.
I too am sceptical of its advantages. I don't think I've ever
seen an actual error in code due to the fact that someone
managed to access a private variable. Doing so generally
requires conscious intent (unlike stepping off the end of an
array, for example), and is not a source of bugs.
Yes, I really do not see the point of adding such a
access checking mechanism.
Also, "trust the programmer" is one of the facets of the
spirit of C language, and C++ inherited it from C language. If
we write well- formed code, the C++ language guarantees the
desired behaviors. If we write ill-formed code, for example,
using low lever method to avoid necessary typing/access
checking, well, it is our problem and it is not fair to ask
the language for help anymore.
It depends. But it's true that the goal has traditionally been
not to impose run-time checks which have a cost in execution
time.
Indeed. If it was an issue in the very beginning, I do not think there
will exist a language called Java.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]