Is it possible to change a C++ object's class after instantiation?

后端 未结 16 1825
忘掉有多难
忘掉有多难 2021-02-02 06:50

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst eac

16条回答
  •  情话喂你
    2021-02-02 07:01

    In addition to other answers, you could use function pointers (or any wrapper on them, like std::function) to achieve the necessary bevahior:

    void print_base(void) {
        cout << "This is base" << endl;
    }
    
    void print_derived(void) {
        cout << "This is derived" << endl;
    }
    
    class Base {
    public:
        void (*print)(void);
    
        Base() {
            print = print_base;
        }
    };
    
    class Derived : public Base {
    public:
        Derived() {
            print = print_derived;
        }
    };
    
    int main() {
        Base* b = new Derived();
        b->print(); // prints "This is derived"
        *b = Base();
        b->print(); // prints "This is base"
        return 0;
    }
    

    Also, such function pointers approach would allow you to change any of the functions of the objects in run-time, not limiting you to some already defined sets of members implemented in derived classes.

提交回复
热议问题