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.
2) "cast" the member variable to remove it's private modifier. I don't
think C++ allows this either.
3) access bar through low-level pointer hacks. This is possible, but
compiler dependant and non portable.
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. :)