Overriding vs Virtual

前端 未结 8 678
星月不相逢
星月不相逢 2020-12-04 18:10

What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as

8条回答
  •  日久生厌
    2020-12-04 18:33

    Suppose we have two classes as follows:-

    class Fruit {
        protected:
        int sweetness;
        char* colour;
        //...
        public:
        void printSweetness() const {
             cout<<"Sweetness : "<

    And now suppose we have some function like the following...

    void f() {
        Fruit* fruitList[100];
        for(int i = 0; i<100 ; i++) {
            fruitList[i]->printInfo();
        }
        return;
    }
    

    In cases like above, we can call the same function and rely on the Dynamic Dispatch Mechanism and the abstraction it provides without knowing what kind of fruits are stored in that array. This simplifies the code to a great deal and increases the readability. And is far far better than using type fields which makes the code ugly!

    Whereas in the overridden method, we must know what kind of object we are dealing with or otherwise face the object slicing problem which may lead to unexpected results.

    Note - I have written this answer just to explicitly show the benefits.

提交回复
热议问题