Non-static private members can be hacked into like so, but what about static members?
class Foo {
private:
static std::vector<int> secrets;
}
Suppose I want to test Foo and I need to get at or change the private static stuff. If it's supposed to stick around as a permanent unit test, it would make sense to just declare friend class FooTest;, but maybe it's not so permanent and I prefer to keep things clean. Or maybe I just can't edit Foo for whatever reason. Can I hack it?
Yes, even though it is trivial to modify this answer for
staticmember instead of a non-static member, here is the working modified example. The only thing that is different here from the original answer is the syntax used for astaticfield. Everything else is the same as the original answer.Working demo
You can also use lvalue reference instead of pointers in the above example so that you don't have to dereference the result of
getagain and again. Demo with lvalue reference instead of pointer