Why do we need virtual functions in C++?

前端 未结 26 3909
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

26条回答
  •  生来不讨喜
    2020-11-21 06:11

    Here is complete example that illustrates why virtual method is used.

    #include 
    
    using namespace std;
    
    class Basic
    {
        public:
        virtual void Test1()
        {
            cout << "Test1 from Basic." << endl;
        }
        virtual ~Basic(){};
    };
    class VariantA : public Basic
    {
        public:
        void Test1()
        {
            cout << "Test1 from VariantA." << endl;
        }
    };
    class VariantB : public Basic
    {
        public:
        void Test1()
        {
            cout << "Test1 from VariantB." << endl;
        }
    };
    
    int main()
    {
        Basic *object;
        VariantA *vobjectA = new VariantA();
        VariantB *vobjectB = new VariantB();
    
        object=(Basic *) vobjectA;
        object->Test1();
    
        object=(Basic *) vobjectB;
        object->Test1();
    
        delete vobjectA;
        delete vobjectB;
        return 0;
    }
    

提交回复
热议问题