What does the virtual keyword mean when overriding a method?

前端 未结 4 884
生来不讨喜
生来不讨喜 2021-01-11 12:16

What does the keyword virtual do when overriding a method? I\'m not using it and everything works fine.

Does every compiler behave the same in this

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 13:07

    Extending on Light Races answer, maybe this will help some people to see what it is doing.

    struct Base {
    public:
        void foo() {
            printf_s("Base::foo\n");
        }
    };
    
    struct Derived : Base {
        void foo() {
            printf_s("Derived::foo\n");
        }
    };
    
    struct BaseVirtual {
    public:
        virtual void foo() {
            printf_s("BaseVirtual::foo\n");
        }
    };
    
    struct DerivedVirtual : BaseVirtual {
        virtual void foo() {
            printf_s("DerivedVirtual::foo\n");
        } 
    };
    
    Derived d;
    d.foo(); // Outputs: Derived::foo
    
    Base& b = d;
    b.foo(); // Outputs: Base::foo
    
    DerivedVirtual d2;
    d2.foo(); // Outputs: DerivedVirtual::foo
    
    BaseVirtual& b2 = d2;
    b2.foo(); // Outputs: DerivedVirtual::foo
    
    

提交回复
热议问题