Can we have a static virtual functions? If not, then WHY?
C++Static MethodsVirtual FunctionsC++ Problem Overview
> Possible Duplicate:
> C++ static virtual members?
Can we have a static virtual functions? If not, then WHY?
class X
{
public:
virtual static void fun(){} // Why we cant have static virtual function in C++?
};
C++ Solutions
Solution 1 - C++
No, because it doesn't make any sense in C++.
Virtual functions are invoked when you have a pointer/reference to an instance of a class. Static functions aren't tied to a particular instance, they're tied to a class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.
Solution 2 - C++
That would make no sense. The point of virtual member functions is that they are dispatched based on the dynamic type of the object instance on which they are called. On the other hand, static functions are not related to any instances and are rather a property of the class. Thus it makes no sense for them to be virtual. If you must, you can use a non-static dispatcher:
struct Base
{
static void foo(Base & b) { /*...*/ }
virtual ~Base() { }
virtual void call_static() { foo(*this); /* or whatever */ }
};
struct Derived : Base
{
static void bar(int a, bool b) { /* ... */ }
virtual void call_static() { bar(12, false); }
};
Usage:
Base & b = get_instance();
b.call_static(); // dispatched dynamically
// Normal use of statics:
Base::foo(b);
Derived::bar(-8, true);