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

后端 未结 16 1806
忘掉有多难
忘掉有多难 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:09

    You can do what you're literally asking for with placement new and an explicit destructor call. Something like this:

    #include 
    #include 
    
    class Base {
    public:
        virtual void whoami() { 
            std::cout << "I am Base\n"; 
        }
    };
    
    class Derived : public Base {
    public:
        void whoami() {
            std::cout << "I am Derived\n";
        }
    };
    
    union Both {
        Base base;
        Derived derived;
    };
    
    Base *object;
    
    int
    main() {
        Both *tmp = (Both *) malloc(sizeof(Both));
        object = new(&tmp->base) Base;
    
        object->whoami(); 
    
        Base baseObject;
        tmp = (Both *) object;
        tmp->base.Base::~Base();
        new(&tmp->derived) Derived; 
    
        object->whoami(); 
    
        return 0;
    }
    

    However as matb said, this really isn't a good design. I would recommend reconsidering what you're trying to do. Some of other answers here might also solve your problem, but I think anything along the idea of what you're asking for is going to be kludge. You should seriously consider designing your application so you can change the pointer when the type of the object changes.

提交回复
热议问题