I'm wondering if there is a way how to reimplement a non-virtual function foo in a 3rd party class Base.
The motivation is that I just need to append a callback into foo. However, the function is called from many places of the class Base, and since it is not virtual, it would require to either change the Base in place, or to dramatically rewrite implementation of the class that will derive from Base. I would like to avoid both scenarios.
I do not need polymorphism at all, the derived class will have just one instance and the type will be known at compile-time (so e.g. CRTP instead of virtualization would suffice too).
I tried to use a class, which inherits from an auxiliary class that declares foo as virtual, but with no luck. Here is an example, where bar simulates any place of Bases implementation from which foo could be called:
/// Ideally, do not modify the `Base` at all
struct Base {
void foo()
{
cout << "Base::foo" << endl;
}
void bar()
{
cout << "bar" << endl;
foo(); //< foo is not virtual !
}
};
struct Virtual {
virtual void foo() = 0;
};
struct Virtual_base : Virtual, Base {
void foo() override = 0; //< it still does not affect Base !
};
struct Virtual_derived : Virtual_base {
void foo() override
{
cout << "Virtual_derived::foo" << endl;
Base::foo();
}
};
Well, Virtual_derived::foo does override, but the Base::bar, unsurprisingly, is still unchanged. I also tried the CRTP approach, but obviously with no luck, as it still clashes with the very same issue that Base stays encapsulated.
I'm little afraid that the answer is that it is just impossible.. is it?