简体   繁体   中英

Why is it allowed to overide non-virtual function?

I'm experimneting with inheritance in C++.

struct A {
    virtual void foo(){ std::cout << "foo()" << std::endl; }
    void bar(){ std::cout << "bar()" << std::endl; }
};

struct B : A{
    void foo(){ std::cout << "derived foo()" << std::endl; }
    void bar(){ std::cout << "derived bar()" << std::endl; }
};

struct C : B {
    void foo(){ std::cout << "derived derived foo()" << std::endl; }
    void bar(){ std::cout << "derived derived bar()" << std::endl; }
};

int main()
{

    B* b = new C();
    b->foo();  //derived derived foo()
    b->bar();  //derived bar()
}

LIVE DEMO

Since, the function foo declared as non-virtual in the struct B I expected that B 's function would be called. But foo which one from C was. Why? I change the "virtual status" of the function in B . Why is it still virtual?

foo() is declared as virtual function in the base class A , so foo() in all the derived class will be virtual too.

From the standard, 10.3$2 Virtual functions [class.virtual] (bold by me)

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 (8.3.5), cv-qualification, and ref-qualifier (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.

Once virtual always virtual.

Since foo is virtual in A it will be virtual in all classes derived from A - whether or not they get the virtual keyword.

Above mention answers are valid, but can we use override keyword, because

The override special identifier means that the compiler will check the
base class(es) to see if there is a virtual function with this exact
signature. And if there is not, the compiler will indicate an error.

so something like this is struct B :

void bar() override

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM