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++?
};
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++?
};
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);
Base
be at runtime except Base
? –
Homework static
doesn't just mean that it can be called without an instance of the class; it's also a promise that it will not access this
. It somewhat approximates a pure function (like constexpr
, which apparently also prohibits virtual
). A function can be both pure (in the mathematical sense) and also virtual. C++ merely mandates that such a function receive a spurious this
pointer which takes away the possibility of imposing the static
contract on derived classes. –
Video const
qualify such a method, which is a more conventional way of hinting purity –
Mosier static virtual
obviously would not work the same way normal static would, there is more than one part to what "virtual" does. In this case, he's looking for a compiler error if a static function is not defined. The compiler could easily do this while ignoring vtables. Versatile verbs are real. –
Continuation © 2022 - 2024 — McMap. All rights reserved.