Question

Suppose I have the following code

class base
{
    public:
    virtual void MyVirtual() { std::cout << "This is base MyVirtual \n";}
    void NonVirtual()        { std::cout << "This is base NonVirtual \n";}
};

class derA : public base
{
    public:
    void MyVirtual()  { std::cout << "This is derA MyVirtual \n";}
    void NonVirtual() { std::cout << "This is derA NonVirtual \n";}
};


class derB : public derA
{
    public:
    void MyVirtual()  { std::cout << "This is derB MyVirtual \n";}
    void NonVirtual() { std::cout << "This is derB NonVirtual \n";}
};

int main()
{
    derA *da = new derB;
    da->MyVirtual();     // "This is derB MyVirtual \n"
    da->NonVirtual();
    std::cin.get();
    return 0;
}

Now my question is why is MyVirtual Method behaving as virtual when it is not marked as virtual in class derA ?

Was it helpful?

Solution

In C++ inherited virtual functions remain virtual in the derived class even without the virtual keyword. It is considered good practice to write virtual for every inherited function.

Update

As pointed out in the comments in C++ 11 it is considered good practice to include the keyword override immediately after the declarator. This catches a common class of errors and explicitly makes the intention clear in the code.

OTHER TIPS

As per the Standard § 10.3 Point #2

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list , cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

There goes your answer, straight from the standards. So, it doesn't matter if you have used the keyword virtual in your derived class or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top