Why is an overridden virtual function called in the base class at build time?

There is a C ++ program:

# include <iostream>

using namespace std;

class base
{
public:
    base()
    {
        cout<<"base"<<endl;
        f();
    }
    virtual void f() {
        cout<<"base f"<<endl;
    }
};

class derive: public base
{
    public:
        derive()
        {
            cout<<"derive"<<endl;
            f();
        }
    void f() {
        cout<<"derive f"<<endl;
    }
};

int main()
{
    derive d;
    return 1;
}

and outputs:

base
base f
derive
derive f

I wonder why the base f appears?

I want the constructor to expand to:

        cout<<"base"<<endl;
        this.f();

But this should indicate in order to determine why the base f is being printed?

+4
source share
1 answer

At the time of construction in the base layer constructor, the actual type of the object base, although it continues to become derived. The same thing happens when destroyed, by the way, and you can also check the type with typeid.

0
source

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


All Articles