Replacing a C++ base class method? -


i have seen is possible replace method @ runtime in c/c++?, of c++ newbie, , cannot yet see how (and if) applies case, i'd try asking example.

in example below, assume classes mybase, a1, , a2, come library, , i'm using them in 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 10: " << _a1.getval(10) << endl;   cout << "a2 10: " << _a2.getval(10) << endl;   return 0; } 

now, let's leave library untouched, i've discovered bug in mybase::getbaseval, in right value returned should inval + 6; instead of given inval + 5;. so, nothing complicated, access input arguments of method needed.

so have option, define new function, say:

int getnewbaseval(int inval) {   return inval + 6; } 

.. , somehow "replace" old mybase::getbaseval:

  • on class level (that is, mybase "patched"), such subsequent instantiations of a1 , a2 use getnewbaseval when getvals called;
  • on object level, such particular instantiation of, say, a1 object (like _a1) use getnewbaseval when getval called;

... writing code @ start of main function?

the long , short of can't; @ least, not within given constraints (which rule out various sub-optimal hacks, such andrey's!).

get library author fix bug, , build own forked , fixed version of in meantime.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -