Chirag Darji
Jan 27, 2021

Can static functions be virtual in C++?

In C++, Static member function of class can not be virtual. Example for below program gives compilation error.

#include<iostream>

using namespace std;

class Test

{

public:

// Error: Virtual member functions cannot be static

virtual static void fun() { }

};

The static member function can’t access non-static data members/functions of a class. The vPTR is non-static data member, hence a static member function can’t access vPTR.

So, since it can’t access vPTR, thus it can’t access vTABLE and thus Runtime Polymorphism is not possible.

Chirag Darji
Chirag Darji

Written by Chirag Darji

0 Followers

Senior Software Engineer. Passionate Software Engineer with 4+ years of experience. Talks about #Java #DSA #LLD #HLD #Distributed Systems #CloudComputing

No responses yet