What does the virtual keyword mean when overriding a method?

Viewed 8792

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 regard?

Should I use it or not?

4 Answers

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

Related