Tom wrote:
[color=blue]
> Let's say I've got a class defined in a header file.
>
> class foo {
> private:
> ...
> int bar;
> ....
> };
>
> Now lets say I have a function that needs to access the private variable
> bar:
>
> void function() {
> ...
> foo x;
> x.bar = 5; // illegal, bar is private
> }
>
> Of course, the normal way to do this is with a friend declaration. But
> lets say I have a constraint where I cannot modify the header file.
> Basically, I don't want to change anything inside the class foo {...}
> declaration. Is there any other way to get access to x.bar from
> function()?
>
> Things that come to mind:
>
> 1) make the friend declaration outside the header file. It would be
> nice if something like this worked:
> foo::friend void main();
> But I can't find any syntax that accomplishes this, so I'm thinking it
> isn't possible.[/color]
It's not possible because it defeats the point of privacy and friendship.
When I inspect the header file X.h, I only need to read the file to know
what's private, what's restricted, and what's public.
[color=blue]
> 2) "cast" the member variable to remove it's private modifier. I don't
> think C++ allows this either.[/color]
Privacy is not a type or qualification, it is an access.
[color=blue]
> 3) access bar through low-level pointer hacks. This is possible, but
> compiler dependant and non portable.[/color]
They are portable when they use offsetof(). It portably returns the offset
of a member; you typecast the address of an object to
[color=blue]
> Are there any other options? I've got my shotgun loaded and pointing in
> the vicinity of my foot, now I just need to figure out how to remove the
> safety lock. :)[/color]
The other option is to modify that header file, or use the interface of its
constituents the way they were designed to be used.
You could also write this above the header:
#define private public
The C++ Standard undefines the act of re-defining a keyword above the
#include for a Standard header file. It also undefines the result of linking
two translation units that disagree on the exact definition of a class they
share (one definition rule). But nobody checks these violations...
However, in this case, the bullet /might/ go thru your foot with only minor
soft-tissue damage, so try it!
--
Phlip
http://industrialxp.org/community/bi...UserInterfaces