Home > Enterprise >  Is it possible to replace member function to a noop function?
Is it possible to replace member function to a noop function?

Time:05-03

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

Ex.

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

void noop(){
; // noop
};

int main(){
 Hi hi();
 hi.test = noop; // just example, not real case

 return 0;
}

Is that possible to replace test() of class Hi to a noop function in runtime!? Thanks.

CodePudding user response:

You can't replace any function at runtime, whether class member or not.

However, you can achieve the desired effect by using a variable.
(This is yet another example of the "add a level of indirection" method of solving problems.)

Example:

class Hi {
public:
    Hi(): test([this]() { do_test(); }) {}
    std::function<void()> test;
    void do_test() { cout << "test" << endl; }
};

void noop(){}

int main(){
 Hi hi;
 hi.test(); // Outputs 'test'
 hi.test = noop;
 hi.test(); // Does nothing
}

CodePudding user response:

You have to think object oriented. In this case you have to elevate your function to be an object we can name it MethodClass then your function in the class Hi will be a pointer to that class. Below a simple example

#include <memory>

class BaseMethodClass
{
public:
    virtual void method() = 0;
};

class MethodClass1 : public BaseMethodClass
{
public:
    virtual void method() 
    { 
        // your implementation here 
    }
};

class MethodClass2 : public BaseMethodClass
{
public:
    virtual void method() 
    { 
        // your implementation here
    }
};
        
class Hi 
{
public:
    Hi() { method = nullptr; };

    void setMethod(BaseMethodClass* m) { method.reset(m); }

    void test() { if (method) method->method(); };

private:
    std::shared_ptr<BaseMethodClass> method;
};

int main() 
{
    Hi hi;
    hi.setMethod(new MethodClass1());
    hi.test();
    hi.setMethod(new MethodClass2());
    hi.test();

    return 0;
}

This way you can override your methos as you want not just noop

  • Related