Given a base class A, with the A::get and A::add functions defined.
class A {
public:
int get() { return 3; }
int add() {
return get() + get();
}
};
Note that A::add calls A::get. Is there a way a derived class B can call A::add but use it’s own B::get function? Something like:
class B : public A {
int get() { return 7; }
};
#include <iostream>
int main() {
A foo;
std::cout << foo.add() << std::endl;
B bar;
std::cout << bar.add() << std::endl;
return 0;
}
Where the expected output is 14 not 6 in the second case. If had control over A, I could make ::get a virtual function and each derived class could implement it as needed. However, lets assume that A is immutable – how do I call the correct ::get?
No, this is not possible: imagine that
Ais compiled separately and given to you as a pre-compiled library to see why.Since
A::getis not virtual, the compiler inserts a call straight toA::get, without any indirection through vtable, into its output forA::add. Moreover, the compiler could even inline the call if it chooses to do so, “baking in” the return of3into its output.