Static Virtual Methods

Terminology

class
class definition (example: class foo { ... }
object instance
an instantiation of a class (example: foo f; or foo *p = new foo;)
virtual
a method declared in a base class or (an interface) that can be overridden in derived (or implementing) classes
static
a class method that does not require (or have) an object associated with it

Description

A virtual static is useful when you need a hierarchy of overridable methods, but don't have an object instance to access the hierarchy.

This concept doesn't really make sense in most languages, including C++. The reason being that virtuals belong in the vtable, and the vtable lives in an object instance. However, if you have access to the type system, like Glib give you, then this can be a very powerful concept.

I'll illustrate this with an example of it's usage:

For the sake of encapsulation, we want every object that represents an "app" to implement an interface called IAllowCreation, which contains 1 method: bool allow_creation(Credentials c);

Lets say we have 2 classes: App1 and App2, both implementing IAllowCreation, and each verifying the Credentials against permissioning databases to see if the creating user is allowed to create this "app".

Now let's say I want a to be able to create an app given it's class name. The Glib type system already allows this by looking up the class type in a registry containing string to classtype mappings. I can create a generic factory that will create any class given it's name as a string by using this registry. This generic factory knows nothing of App1 or App2 permissioning logic. It's job is just to look up the class type via the Glib type system and create an instance.

Before it can create however, it must check the permissions via the IAllowCreation::allow_creation() method. The problem here is that we haven't created App1, therefore we can't call its allow_creation() method.

This is where we need a virtual static. Basically, since we have information about App1's class (via introspection/reflection), we can see that it implements an IAllowCreation. We can then find the implementation of that class's allow_creation() method. This of course would just be a function pointer. We would call the function pointer with NO object instance, because there is none. Based on it's return value, we would know whether to go ahead and actually create the object instance.

The fact we are creating it with no object instance, and have no object instance involved anywhere makes this allow_creation() method a static.

The fact that we never know about the App1 class itself and only the interface which they implement, makes the allow_creation() method a virtual.

TADA! static virtuals!