-2

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.

shinzou
  • 5,850
  • 10
  • 60
  • 124

2 Answers2

2

In your code, next->print(); won't be called at all. If you could debug it, you'll find next is null here.

LIVE

EDIT

With your edited code, the process will be infinate. next->print(); will lead to B::print(), even though the static type of next is A*, but A::print() is a virtual function, and next is pointing to an instance of B in fact, so dynamic polymorphism works here.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • It does now. The OP did post a complete example. I removed my comment. – NathanOliver Feb 02 '16 at 13:49
  • But in my other question here: http://stackoverflow.com/a/35095397/4279201 I was told that name look up is based on static type, so in this case, shouldn't a pointer of `A` look for a function of `A` regardless of what type it points to? – shinzou Feb 02 '16 at 14:00
  • @kuhaku name lookup and virtual dispatch are two separate things. The name `print` is only looked up from the type `A`, but because it happens to be a virtual function, the call will be dispatched virtually. – eerorika Feb 02 '16 at 14:04