Philipp wrote:
Thomas J. Gritzan wrote:
>Philipp schrieb:
>>Hello
I don't exactly understand why there are no static virtual functions. I
Because virtual functions depend on the actual object you call the
function with. But static functions don't need objects.
I think of "virtual" as "gets overriden by derived classes", is this
wrong?
That's right. The override that is chosen depends on the dynamic type of the
object that you call the virtual function for. But here's the trouble. A
static member function has no object, hence no dynamic type, so there is no
way to choose which function to actually call. Example:
#include <iostream>
class Base
{
public:
virtual void test() { std::cout << "Base\n"; }
};
class Derived1 : public Base
{
public:
virtual void test() { std::cout << "Derived1\n"; }
};
class Derived2 : public Base
{
public:
virtual void test() { std::cout << "Derived2\n"; }
};
int main()
{
Base b;
Derived1 d1;
Derived2 d2;
Base* p = &b;
p->test(); // Prints "Base"
p = &d1;
p->test(); // Prints "Derived1"
p = &d2;
p->test(); // Prints "Derived2"
}
Simple inheritance. Now with static virtuals (assuming they were allowed):
#include <iostream>
class Base
{
public:
static virtual void test() { std::cout << "Base\n"; }
};
class Derived1 : public Base
{
public:
static virtual void test() { std::cout << "Derived1\n"; }
};
class Derived2 : public Base
{
public:
static virtual void test() { std::cout << "Derived2\n"; }
};
int main()
{
Base::test(); // Prints Base
Derived1::test(); // Prints Derived1
Derived2::test(); // Prints Derived2
}
Now there is nothing dynamic anymore. The function to be called is chosen
statically. So what would the virtual keyword be good for? How and why
would the compiler at runtime choose which of those three functions to
call?
In that sense, I was expecting that a static function could be overriden
by a derived class (ie: function is virtual _and_ static).
From your explaination I understand that this is a compiler /
optimization issue.
No, it's a logic issue. Having a function that is both virtual and static
makes no sense.