Possible to replace member function to a noop function?

I write c++ with c++11 and have a question as title.

Ex.

class Hi {
public:
Hi(){};
test() {cout << "test" << endl;};
}

void noop(){
; // noop
};

Is that possible to replace test() of class Hi to noop in runtime!? Thanks.
This is an XY problem. That is, it appears that you are asking about a potential solution to a problem that you haven't explained.

See https://xyproblem.info/
.
Last edited on
You have to use some kind of indirection. Typically, you store a pointer to a function, and conditionally call it.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <functional>
#include <iostream>

struct Thing {
    using init_func = std::function<void(void)>;

    Thing(init_func init = nullptr) : on_init(init) {
        if (on_init)
            on_init();
    }

    init_func on_init = nullptr;
};

int main() {
    auto noop = []() -> void {
                    std::cout << "noop\n";
                };
    Thing thing(noop);
}
alternately:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Hi 
{
  public:
  Hi(){};
  void test() {cout << "test" << endl;}
  void test2(){cout << "Hi!" << endl;}
};

class Hi2 : public Hi
{
  public:
  void test() {};
};

int main ()
{
  Hi h;
  Hi2 h2;
  cout <<"testing Hi\n";
  h.test();
  h.test2();
  cout <<"testing Hi2\n";
  h2.test();
  h2.test2();
  cout << "casting \n";
  ((Hi2*)(&h))->test(); //makes an object of Hi class type use the empty override!
}


if you are trying to fix a large amount of code that already uses the object so that sometimes it has an alternate method... it depends. If you are allowed to tamper with the original object, perhaps there is a simpler way:
1
2
3
4
5
6
7
8
9
void test(bool b = true)
{
   if(b)
    {
      //original body
    }
   //implied else do nothing
}

..
that makes the parameter optional for the previous/existing code:
thing.test();//will do the original code
newthing.test(false);//will not do the original code

if you cannot or should not (eg, 3rd party) tamper with it, derived solution will work and your new code or modified code can cast or replace.
Last edited on
Registered users can post here. Sign in or register to post.