Invoking a 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 into B::internal_init(), as expected. Then, to A::init()(I think, since B comes from A and B doesn't have any init()). Now what?

which internal_init()one will he choose? as it goes into B::internal_init(), the program will go into an endless loop, and I don't understand why.

  • What really happens when I call internal_init()?
  • why does it call internal_init()part "B" of the instance? Is this about the "virtual"? If so, how did it happen? Virtual functions are executed when we use polymorphism (which, like the beginner, like me, understands that it works with pointers to the base class that point to objects of the derived class).
+4
2

instance B

instance.internal_init();

B internal_init(). internal_init() init();. - , .

, A init(), B. init() internal_init();, B. internal_init() B, B internal_init().

segfault stack.

+7

-, struct B struct A - struct B: public A. internal_init of A B, virtual A.

, : instance.internal_init(); internal_init() B, A::init, B::internal_init() .. , . ( , , ), internal_init() A B init():

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

Source: https://habr.com/ru/post/1607480/


All Articles