virtual function in parent of parent class [duplicate]
Asked Answered
G

2

5

The following code is late binding test() method but shouldn't it bind early? because test() method is not virtual in class B(but in class A), and we are using pointer of class B.

class A{
    public:
        virtual void test(){
            cout<<"test a";
        }
};
class B : public A{
    public:
        void test(){
            cout<<"Test b";
        }
};
class C: public B{
    public:
        void test(){
            cout<<"test c";
        }
};
int main(){
    B *bp;
    C objc;
    bp = &objc;
    bp->test();  // test c
}
Geneticist answered 12/5, 2016 at 9:30 Comment(1)
test is virtual in all classes here; the virtual keyword does not need to be repeated.Hoop
S
5

Once a function has been declared virtual in a class, it's always virtual in the classes that inherit from that class, whether you use the virtual keyword or not.

So in your class C, the test() function is actually overriding B and A's own test() functions.

Silvern answered 12/5, 2016 at 9:35 Comment(0)
H
4

N4296, 10.3§2 (draft version):

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.

Emphasis by me.

A virtual function remains virtual in all derived classes, regardless if it is declared as virtual in the derived classes.

Heterosporous answered 12/5, 2016 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.