I am very confused with static functions. Can I override them? If no, then why? I searched web a lot but i am still not clear. Please tell with one example if possible. Thanks a lot.

3 Years
Discussion Span
Last Post by Duoas

Static functions are class-specific. You can declare/define functions with the same signature for other classes, but static functions either have to be accessed with classname::functionname() if accessed outside of the class, or simply functionname() if inside the class. They are NOT inherited by sub-classes. So, overriding them doesn't work like it would for member functions.


To be clear, no, you cannot override static methods. (You can overload them, though.)

The reason is simple: a static method cannot appear in a class's virtual function table, so it is not inherited. In order to call a static method you must know exactly what type of object you are calling it from.

A quick example:

#include <iostream>

struct Foo
  static void speak()
    std::cout << "Hello\n";

struct Bar: public Foo
  static void speak()
    std::cout << "No.\n";

int main()
  Foo* baz = new Bar;

Give it a run.

Even though it is actually a Bar you've got, the compiler sees that you've got a pointer to a Foo and calls Foo::speak().

What would you have to do to make it say "No"?

That's right. Cast.

static_cast <Bar*> (baz)->speak();

By now, you may wonder if using the pointer stuff isn't overkill.

Well, actually, it is. You might as well just call the static methods directly.


Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.