简体   繁体   中英

calling virtual method without pointing to an object?

#include <iostream>

struct A {
    void init()
    {
        internal_init();
    }
    virtual void internal_init()
    {
        std::cout << "internal of A" << std::endl;
    }
};

struct B: public A {
    void internal_init()
    {
        init();
        std::cout << "internal of B" << std::endl;
    }
};

int main(){
    B instance;
    std::cout << "internal of A" << std::endl;
    instance.internal_init();
    return 0;
}

First the program goes to B::internal_init() as expected. Then, to A::init() (I guess since B derives from A , and B doesnt have any init() ). Now what?

what internal_init() it will choose? since it goes to B::internal_init() ,the program will go into and infinite loop, and I don't understand why.

  • What really happens when I call internal_init() ?
  • why it calls internal_init() of the "B part" of the instance? Is this about "virtual"? If so, how come? Virtual functions take place when we use polymorphism (which as far as a beginner like my self understands, it's working with pointers of a base class that point to a derived class objects).

Since instance is a B

instance.internal_init();

Will call B s internal_init() . Then in internal_init() you call init(); . Now member functions have an implicit parameter that is the this pointer.

So when we call A 's init() the this pointer is actually a B . In init() we call internal_init(); using the this pointer to a B . Since internal_init() is virtual and we have a pointer to B the virtual lookup mechanism will call B 's internal_init() .

This then loops again and will eventually cause a segfault or stack overflow.

Firstly struct B inherits all functions of struct A because of struct B: public A . The function internal_init of A is overridden in B because you use the same function signature and the keyword virtual in A .

So now the calls are: instance.internal_init(); which calls internal_init() of B , which calls A::init , which calls B::internal_init() , etc. until a segmentation fault is given. To prevent this (and I think this is what you want), you can explicitly call the internal_init() of A in B instead of calling init() :

struct B: public A {
    virtual void internal_init()
    {
        A::internal_init();
        std::cout << "internal of B" << std::endl;
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM