1

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?

Dmitry J
  • 867
  • 7
  • 20

1 Answers1

0

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.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • Ok, I think I see the point. `A::bar()` and `C::bar()` are completely different functions and them having the same name doesn't change this fact. I could not hope to call `C::other_bar()` from `A::foo()` without overriding it, so I can't do it with `C::bar()` either. – Dmitry J Nov 27 '16 at 02:06