Is having static virtual functions possible in C++ ?
I know its not as compiler throws an error but I am eager to know why?

the one reason I can think of (please validate)

"Virtual Functions are related to the object i,e calling a right functon on right object where as static functions scope is at the class level. So there is a wide gap between the two concepts hence it is not possible"

I know the reasoning above looks stupid but can you provide some solid grounds to it ?

Polymorphism occurs because of dynamic binding, which is made possible through use of pointers (The compiler internally represents a virtual function as a pointer, whose value is determined at run time) -

however, a static function is just that - its not a function pointer, but an object which has a static address.

If you want to call a derived class static function through a base class pointer, then you can use a non-static virtual function wrapper to achieve the same thing. eg,

#include <iostream>

class Base
{
    static void foo() { std::cout << "Base\n"; }
public:
    virtual void bar() { foo(); }

};

class Derived : public Base
{
    static void foo() { std::cout << "Derived\n"; }
public:
    virtual void bar() { foo(); }
};

int main()
{
    Base* obj = new Derived;
    obj->bar();
    delete obj;
}

>Is having static virtual functions possible in C++ ?
No.

>I know the reasoning above looks stupid but can you provide some solid grounds to it ?
No, actually your reasoning is precisely what I would use to describe the restriction. The real answer is a little more involved though.

>however, a static function is just that - its not a function
>pointer, but an object which has a static address.
You're probably thinking of the usual way of accessing a static member function:

MyClass::my_static_function();

Expecting polymorphic behavior in this case is silly unless you use templates for compile-time polymorphism:

#include <iostream>

using namespace std;

class Foo {
public:
  static void bar() { cout<<"bar\n"; }
};

template <typename T>
void baz()
{
  T::bar();
}

int main()
{
  baz<Foo>();
}

But there's nothing in the language definition that prevents adding virtual static member functions. In fact, it would be rather simple to add the feature. The class calling mechanism ( MyClass::my_static_function(); ) would work the same and an extra rule could be added so that obj->my_static_function(); calls the most derived static member function.

virtual static member functions aren't presently supported in C++, but it's not because they're impossible or illogical. It's more likely to be an oversight followed by lack of demand.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.