Virtual Static Idiom

The Virtual Static Idiom is a very simple technique used in C++ to make static methods virtual. This way, static methods can be overridden by subclasses.

Actually, it just binds a static (class) method to an instance by explicitly passing the this pointer. This is more powerful than allowing polymorphic static methods because it makes the static method really a part of an instance.

Note how because the static method is part of the class Foo, it has access to all parts of Foo.

The example below is particularly useful when you have to pass a callback function into a system call, typical practice in Windows. You get one thunk that takes one void * as its parameters.

It can also be useful to explicitly type the incoming this pointer to a Foo *.

 class Foo
 {
 public:
     Foo();

protected: // Virtual static idiom <-- StaticCallback?() virtual bool Callback();

private: // Virtual static idiom --> Callback() static bool StaticCallback?( void *pThis ) { assert( pThis ); return ((Foo *)pThis)->Callback(); } };

Popular uses:


After meditating on this pattern for about 20 minutes, I just cannot see how this can be useful, in any way, at all. Can a real-world example of its utility be demonstrated, perhaps written in LiterateProgramming style? --SamuelFalvo?

You may wish to meditate a bit more upon: "when you have to pass a callback function into a system call, typical practice in Windows". Standard 'C'-style callbacks are done with (void(*)(void*)). Essentially this is acting as a wrapper for a C callback. This follows the principle: every problem in programming can be solved by an extra layer of indirection... except for the problem of too much indirection. In a language designed for EventDrivenProgramming and providing real 'thunks' this wouldn't be an issue. And it is subject to all sorts of problems in C/C++, such as figuring out when it is appropriate to delete the 'Foo' after using it in this manner.


I think this is not a pattern but an AntiPattern, and the solution is the SingletonPattern

I think you don't understand which problem is being solved and thus do not comprehend why the SingletonPattern is not a solution.


CeePlusPlusIdioms, AreDesignPatternsMissingLanguageFeatures


EditText of this page (last edited July 9, 2010) or FindPage with title or text search