I have seen Is it possible to replace a method at runtime in C/C++?, but I am something of a C++ newbie, and so cannot yet see how (and if) it applies to my case, so I'd like to try asking with my example.
In the example below, assume classes MyBase
, A1
, and A2
, come from some library, and I'm using them in my main
:
// g++ -std=c++11 -o test.exe test.cpp
#include <iostream>
using namespace std;
class MyBase {
public:
MyBase() { }
~MyBase() { }
int getBaseVal(int inval) {
return inval + 5;
}
};
class A1 : public MyBase {
public:
A1() : MyBase() { }
~A1() { }
int getVal(int inval) {
return getBaseVal(inval) + 10;
}
};
class A2 : public A1 {
public:
A2() : A1() { }
~A2() { }
int getVal(int inval) {
return getBaseVal(inval) + 20;
}
};
int main() {
A1 _a1 = A1(); A2 _a2 = A2();
cout << "A1 for 10: " << _a1.getVal(10) << endl;
cout << "A2 for 10: " << _a2.getVal(10) << endl;
return 0;
}
Now, let's say I would like to leave this library untouched, but I've discovered a bug in MyBase::getBaseVal
, in that the right value returned should be inval + 6;
instead of the given inval + 5;
. So, nothing complicated, but access to the input arguments of the method is needed.
So do I have an option, to define a new function, say:
int getNewBaseVal(int inval) {
return inval + 6;
}
.. and then somehow "replace" the old MyBase::getBaseVal
:
- On a class level (that is,
MyBase
would be "patched"), such that all subsequent instantiations ofA1
andA2
will ultimately use thegetNewBaseVal
when theirgetVal
s are called; - On an object level, such that only a particular instantiation of, say,
A1
as object (like_a1
) would ultimately use thegetNewBaseVal
when itsgetVal
is called;
... by writing some code at the start of the main
function?