Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 446
Ron_s Avatar asked Aug 29 '11 07:08

Ron_s


People also ask

Can you have a static virtual method?

In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class.

Can static method be virtual C#?

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

What is static virtual?

A static member is something that does not relate to any instance, only to the class. A virtual member is something that does not relate directly to any class, only to an instance. So a static virtual member would be something that does not relate to any instance or any class.

Is virtual function can be friend of another class?

A virtual function can be a friend function of another class. Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism. The prototype of virtual functions should be the same in the base as well as derived class.


1 Answers

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 .

like image 129
Michael Anderson Avatar answered Oct 11 '22 19:10

Michael Anderson