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
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.
First of all, C# doesn't support virtual static method.
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.
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With