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

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

     #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";
        }
    };
    Base* object;
    
    int main() {
        object = new Derived; 
        object->whoami(); 
        Base baseObject;
        object = &baseObject;// this is how you change.
        object->whoami();
        return 0;
    }
    

    output:

    I am Derived                                                                                                                     
    I am Base 
    

提交回复
热议问题