0

This is a minimal example of my problem. I have 2 classes, one is abstract, the other one is derived.

#include <iostream>

class A
{
public:
    virtual void foo() = 0;
    void bar() {
        foo();
        std::cout << "BAR" << std::endl;
    }
};

class B : public A
{
public:
    void foo() {
        std::cout << "FOO" << std::endl;
    }
};

int main()
{
    B b;
    b.bar();
}

The code compiles and gives the expected result: FOO\nBAR. Now to the question: Because the foo-method of class B is completely independent (uses no variables or other methods of B or A), I want foo to become static. Basically I want to call foo with B::foo().

Declaring foo static doesn't work, since foo implements the virtual method from A. How do you handle such a case?

Jakube
  • 3,353
  • 3
  • 23
  • 40
  • 2
    What benefits do you want to obtain by making the function static? Why not just leave it as it is? Also, take a look at that: http://stackoverflow.com/questions/2721846/alternative-to-c-static-virtual-methods?rq=1 – dreamzor Aug 08 '15 at 10:59
  • If the function should really be static, why is it virtual? If it needs to be virtual, [it clearly cannot be static](http://stackoverflow.com/q/1820477/3425536). – Emil Laine Aug 08 '15 at 11:00
  • @dreamzor This is just a minimal example. My actual class(es) have quite large constructors, that I don't want to call. – Jakube Aug 08 '15 at 11:02

2 Answers2

3

You can just add a new static method and have foo call it:

class B : public A
{
public:
    void foo() {
        doFoo();
    }

    static void doFoo() {
        std::cout << "FOO" << std::endl;
    }
};

This way you'll also be able to call it with B::doFoo()

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
0

Undefined behaviour, I guess, but you could try this:

((B*)nullptr)->B::foo();

By calling ->B::foo() instead of ->foo() we skip the vtable lookup, which is good as the nullptr clearly doesn't point anywhere near a real vtable.

This worked for me, but that proves nothing. Undefined behaviour means this might delete all the files on your computer if you run it. So don't really use it.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88