Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function in parent of parent class [duplicate]

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
}
like image 779
Khuram Avatar asked May 12 '16 09:05

Khuram


1 Answers

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.

like image 65
JBL Avatar answered Sep 18 '22 09:09

JBL