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

后端 未结 16 1784
忘掉有多难
忘掉有多难 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 06:58

    You can by introducing a variable to the base class, so the memory footprint stays the same. By setting the flag you force calling the derived or the base class implementation.

    #include 
    
    class Base {
    public:
        Base() : m_useDerived(true)
        {
        }
    
        void setUseDerived(bool value)
        {
            m_useDerived = value;
        }
    
        void whoami() {
            m_useDerived ? whoamiImpl() : Base::whoamiImpl();
        }
    
    protected:
        virtual void whoamiImpl() { std::cout << "I am Base\n"; }
    
    private:
        bool m_useDerived;
    };
    
    class Derived : public Base {
    protected:
        void whoamiImpl() {
            std::cout << "I am Derived\n";
        }
    };
    
    Base* object;
    
    int main() {
        object = new Derived; //assign a new Derived class instance
        object->whoami(); //this prints "I am Derived"
    
        object->setUseDerived(false);
        object->whoami(); //should print "I am Base"
    
        return 0;
    }
    

提交回复
热议问题