Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have a static virtual functions? If not, then WHY? [duplicate]

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++? }; 
like image 890
Jatin Avatar asked Mar 25 '12 18:03

Jatin


People also ask

Can we have static virtual function?

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.

Why static methods are not virtual?

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.

Why we can not declare static member function constant or virtual?

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.

Can we declare a static function as virtual in C#?

First of all, C# doesn't support virtual static method.


2 Answers

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.

like image 185
Oliver Charlesworth Avatar answered Sep 28 '22 02:09

Oliver Charlesworth


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); 
like image 44
Kerrek SB Avatar answered Sep 28 '22 02:09

Kerrek SB