Topic: Who needs friends (was Internal linkage (static, inline,un-ns))
Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1998/09/04 Raw View
Martijn Lievaart wrote:
[...]
>
> Tried this once but came upon several problems.
> 1) Some compilers store the access in the mangled name. In that case it will
> simply not work. (Does this allow for overloading on access? ;^>)
> 2) There is no garantee that the object layout will remain the same when
> changing the access of it's members. I haven't really observed this in
> any compiler though.
>
> If 2 doesn't hold but 1 does, there is another (but very error prone way) to
> achieve the same result. Define a class that is exactly the same as the
> original, but with all private and protected keywords replaced by public.
> Now cast a pointer to the object you want access to to this new class.
> Indeed, we don't need no stinking friends.
If 1 *and* 2 hold, you can still copy the complete class definition
under a new class name (since the definitions are equal, the layouts
will be as well, no matter how complicated the rules are - well,
in theory it's not guaranteed, but I can't see any good reason to
do otherwise - except maybe for a dirty-trick-detector ;-)).
Now add accessor methods for the private and protected variables
(since they are functions, they shouldn't affect the layout),
and use reinterpret_cast. Voila - "unfriendly" access granted.
[...]
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]