Why do we need virtual functions in C++?

前端 未结 26 3653
北恋
北恋 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:19

    I would like to add another use of Virtual function though it uses the same concept as above stated answers but I guess its worth mentioning.

    VIRTUAL DESTRUCTOR

    Consider this program below, without declaring Base class destructor as virtual; memory for Cat may not be cleaned up.

    class Animal {
        public:
        ~Animal() {
            cout << "Deleting an Animal" << endl;
        }
    };
    class Cat:public Animal {
        public:
        ~Cat() {
            cout << "Deleting an Animal name Cat" << endl;
        }
    };
    
    int main() {
        Animal *a = new Cat();
        delete a;
        return 0;
    }
    

    Output:

    Deleting an Animal
    
    class Animal {
        public:
        virtual ~Animal() {
            cout << "Deleting an Animal" << endl;
        }
    };
    class Cat:public Animal {
        public:
        ~Cat(){
            cout << "Deleting an Animal name Cat" << endl;
        }
    };
    
    int main() {
        Animal *a = new Cat();
        delete a;
        return 0;
    }
    

    Output:

    Deleting an Animal name Cat
    Deleting an Animal
    

提交回复
热议问题