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,
MyBasewould be "patched"), such that all subsequent instantiations ofA1andA2will ultimately use thegetNewBaseValwhen theirgetVals are called; - On an object level, such that only a particular instantiation of, say,
A1as object (like_a1) would ultimately use thegetNewBaseValwhen itsgetValis called;
... by writing some code at the start of the main function?