VOOZH about

URL: https://www.geeksforgeeks.org/cpp/can-static-functions-be-virtual-in-cpp/

⇱ Can Static Functions Be Virtual in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Can Static Functions Be Virtual in C++?

Last Updated : 6 Jun, 2022

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. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.

For example, below program gives compilation error,

Output

prog.cpp:9:29: error: member ‘fun’ cannot be declared both virtual and static
 virtual static void fun() {}
 ^

Also, static member function cannot be const and volatile. Following code also fails in compilation,

Output

prog.cpp:8:23: error: static member function ‘static void Test::fun()’ cannot have cv-qualifier
 static void fun() const {}
 ^
Comment
Article Tags: