Why Is virtual keyword "persistent" throughout a hierarchy in C++?

Viewed 291

Suppose I have a function print() in 3 classes A, B, and C. C inherits from B inherits from A. Keyword virtual is only used in A.

Why does both of the following use the print() in C?

    A* ac = new C();
    ac->print(); //C's print() 

    B* bc = new C();
    bc->print(); //C's print(), not B's print() even though virtual is not used.

What is the intuition here?

Full working code below if you want to compile/run it:

#include <iostream>
#include <cstdlib>

using namespace std;

class A{
public:
    A(){
        cout << "construct A" << endl;
    }
    virtual void print(){
        cout << "A says" << endl;
    }
};


class B: public A{
public:    
    B(){
        cout << "construct B" << endl;
    }
    void print(){
        cout << "B says" << endl;
    }    
};

class C: public B{
public:    
    C(){
        cout << "construct C" << endl;
    }
    void print(){
        cout << "C says" << endl;
    }    
    void print(int x){
        cout << "C says " << x << endl;
    }
};


int main(){

    A* ac = new C();
    ac->print();

    B* bc = new C();
    bc->print();

    return 0;
}
3 Answers
Related