Can we have a virtual static method ? (c++)

Ron_s picture Ron_s · Aug 29, 2011 · Viewed 54.7k times · Source

Possible Duplicate:
C++ static virtual members?

Can we have a virtual static method (in C++) ? I've tried to compile the following code :

#include <iostream>
using namespace std;

class A
{
public:
    virtual static void f() {cout << "A's static method" << endl;}
};

class B :public A
{
public:
    static void f() {cout << "B's static method" << endl;}
};

int main()
{
    /* some code */
    return 0;
}

but the compiler says that :

member 'f' cannot be declared both virtual and static

so I guess the answer is no , but why ?

thanks , Ron

Answer

Michael Anderson picture Michael Anderson · Aug 29, 2011

No. static on a function in a class means that the function doesn't need an object to operate on. virtual means the implementation depends on the type of the calling object. For static there is no calling object, so it doesn't make sense to have both static and virtual on the same function .