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++? };
A virtual function cannot be global or static because, by definition, a virtual function is a member function of a base class and relies on a specific object to determine which implementation of the function is called.
It's simple, a static method cannot be overridden by an inheriting class, since it's not inherited. So it's not virtual. What you call "overriding a static method" is actually only defining another static method on another class.
A 'const member function' is not allowed to modify the object it is called on, but static member functions are not called on any object. It is used directly by scope resolution operator. Thus having a const static member function makes no sense, hence it is illegal.
First of all, C# doesn't support virtual static method.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With