Dmitry J Dmitry J - 10 days ago 5
C++ Question

c++ calling static function from virtual function

I have virtual method that calls static method of appropriate class:

class A{
public:
static void bar() {std::cout<<"bar A\n";}
virtual void foo(){
//Some A work...
bar();
}
};

class B : public A{
public:
static void bar() {std::cout<<"bar B\n";}
virtual void foo() override {
//Some B work...
bar(); //prints bar B, as intended.
}
};


But now I want to have class C, with method foo(), with the only difference of calling C::bar() in the end:

class C : public A {
public:
static void bar() override {std::cout<<"bar C\n";}
virtual void foo(){
//Some **A** work...
bar(); //I want to print "bar C" here
}
}


However, here I needed to make full copy of method A::foo definition. I could also introduce dummy virtual method like `virtual void callStaticBar(){bar();} and override it in class C with the same text. Is there more elegant way to do such a thing?

YSC YSC
Answer

No. If C::foo() is not defined, calling foo() on a C instance will really call A::foo(); since class A has no knowing of class C (except is those cases with the vtable), there is no way for A::foo() to call C::bar(), regardless of the fact that the original call came from a C instance.

You need to use your method of dummy virtual method or to tell us more about what you want to achieve, as they might be a better solution in a particular situation.