The Wayback Machine - https://web.archive.org/web/20240213201523/https://www.geeksforgeeks.org/can-static-functions-be-virtual-in-cpp/
Open In App
Related Articles

Can Static Functions Be Virtual in C++?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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,

CPP




// CPP Program to demonstrate Virtual member functions
// cannot be static
#include <iostream>
 
using namespace std;
 
class Test {
public:
    virtual static void fun() {}
};


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,

CPP




// CPP Program to demonstrate Static member function cannot
// be const
#include <iostream>
 
using namespace std;
 
class Test {
public:
    static void fun() const {}
};


Output

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 06 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads