简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM