4

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 it outputs:

base
base f
derive
derive f

I am wondering why base f appears?

I quess in base the constrctor expands to:

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

But this should point to derive so why base f is print out?

Almo
  • 15,538
  • 13
  • 67
  • 95
chang jc
  • 489
  • 8
  • 16

1 Answers1

0

During construction, in the baseclass constructor, the actual type of the object is base, even though it lateron continues to become a derived. The same happens during destruction, btw, and you can also verify the type using typeid.

Ulrich Eckhardt
  • 662
  • 6
  • 14