Search code examples
c++c++11syntaxvirtual-inheritance

About virtual function and inheritance


About the following code:

class A {
    A * next;
    static A* tmp;
public:
    A() : next(tmp) {
        if (tmp)
            tmp->next = this;
        tmp = this;

    }
    virtual void print() {
        if (next)
            next->print();
    }
};
class B : public A {
    int a = 1;
public:
    void print() {
        cout << "foo";
        A::print();
    }
};
A* A::tmp;
int main(){
    B c;
    B b;
    b.print();
}

Why does next->print(); leads to B::print() and not back to A::print()? Since next is a static pointer of A why does it go to B's function?

EDIT: added B c; that I removed accidentally when posting.


Solution

  • Since next is a static pointer of A

    next is not a static pointer. Even though you may have copy-initialized it from a pointer with static storage. But whether it is static has nothing to do with how the member function call works.

    why does it go to B's function?

    Because print is a virtual function. If a pointer A* next points to an instance of B, then next->print() will call B::print(). This is known as virtual or dynamic dispatch.

    If you wanted to call A::print() instead, then you could have used static dispatch:

    next->A::print();
    

    Of course, if you only ever want to use static dispatch, then it doesn't make any sense to declare the function virtual in the first place.