0

Is there a way to call the static member function override B::baz() from the base class member function A::foo()?

class A
{
public:
  virtual void foo() { bar(); baz(); }
  virtual void bar() { std::cout << "A::bar()" << std::endl; };
  static void baz() { std::cout << "A::baz()" << std::endl; }
};

class B : public A
{
public:
  void bar() override { std::cout << "B::bar()" << std::endl; };
  static void baz() { std::cout << "B::baz()" << std::endl; }
};

The output of

B b;
b.foo();

is

> B::bar()
> A::baz()

so A::baz() is called in A::foo().

DrPepperJo
  • 632
  • 1
  • 5
  • 19
  • why do you feel the need to do this? – Neil Butterworth Nov 14 '22 at 01:42
  • No, a static method to be able to call a function without an object (an instance). So, in fact, `A::bar` and `B::bar` are two different function, and compiler knows which is called in compiled time. – GAVD Nov 14 '22 at 01:44
  • [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) is one common way to solve this. – Yksisarvinen Nov 14 '22 at 01:44
  • @NeilButterworth The base class calls a framework function that takes a function pointer. For each derived class, the function pointer needs to point to a different function. – DrPepperJo Nov 14 '22 at 01:49
  • @DrPepperJo Well, the 'overriding `static` method' might be an overkill in such a case. Why not let each subclass register itself, choosing how it wants to do that? (`static` method of chosen name, lambda, free function)? – Yksisarvinen Nov 14 '22 at 01:52
  • You might be letting yourself be misled by convenient shorthand. The convenient `virtual void foo() { bar(); baz(); }` is shorthand for `virtual void foo() { this->bar(); A::baz(); }`. When viewed this way, does it still look like overriding `baz()` is plausible? – JaMiT Nov 14 '22 at 04:25

0 Answers0