Re: Accessing non-static class members fom static methods (About
We generally access non-static class members from a static method by passing
"this" to that static method and accessing non-static members over "this".
My alternative is caching "this" into a static member and use that static
member whenever you need to access non-static members. Is there anything bad
about this solution?
First, if static member functions are called from non-static ones, with the
pointer updated to the "current" instance, it lets you violate constness without
I.e., you have then -- not that you're doing it below -- effectively
prevented the compiler from telling you about such constness violations.
Second, it assumes there is ever only one object of class Foo, or that you're
only interested in the last object instantiated from Foo.
Third, that's very dangerous with respect to that object's lifetime: it's
possible to make the static member functions use a dangling pointer, one that no
longer points to a valid object.
However, the second and third points can be circumvented by making Foo a
But a much better solution then is to make the current static member functions
into non-static member functions (look up "Meyers singleton").
static Foo * lpThis;
// Some initializations...
lpThis = this; // Last statement in the constructor...
static void doJob ()
// Now we can access all non-static members over static "lpThis"...
Foo * Foo::lpThis;
Thanks in advance.
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
Q: What is the most annoying thing on usenet and in e-mail?