C++构造函数与析构函数中调用虚函数

在基类和派生类的构造函数和析构函数中调用虚函数,会不会体现出多态性呢?Jungle做了以下测试:

  1. 首先定义了基类Base和虚函数fun,并在构造函数和析构函数中调用了fun();
  2. 然后定义了派生类Derived1继承了Base,并重写了虚函数fun(),并在Derived的构造函数和析构函数中调用了fun();
  3. 接下里测试。
class Base {
public:
    Base()
    { 
        cout<<"Base::Base()"<<endl;
        fun();
    }
    virtual ~Base()
    {
        cout<<"Base::~Base()"<<endl;
        fun();
    }
    virtual void  fun()
    {
        cout<<"Base::fun() virtual"<<endl;
    }

};
class Derived1:public Base
{
public:
    Derived1()
    {
        cout<<"Derived1::Derived1()"<<endl;
        fun();;
    }
    ~Derived1()
    {
        cout<<"Derived1::~Derived1()"<<endl;
        fun();
    }
    virtual void fun()
    {
        cout<<"Derived1::fun() virtual"<<endl;
    }
};

int main()
{
    Base *b = new Base();
    delete b;
    cout<<endl;

    Derived1 *d = new Derived1();
    delete d;
    cout<<endl;

    Base *bd = new Derived1();
    delete bd;
    cout<<endl;

    system("pause");
    return 0;
}

这里写图片描述
结果分为三段,第一段不必说明。
第二段,Derived1 *d = new Derived1();时,先调用类构造函数,并且fun()是基类的fun(),因为此时派生类还不存在。然后才构造派生类。析构时,先析构派生类,并调用派生类的fun(),再析构基类。
第三段,基类指针指向派生类对象。构造时,先调用基类的构造函数,此时构造函数中调用了fun(),可以看到,这个fun是基类的fun(),这里“虚函数的动态绑定机制并没有会生效”,这是因为此时派生类还不存在。析构时,先析构派生类,派生类中的fun()调用的是自己的fun(),然后析构基类,基类析构函数中的fun()调用的是基类的fun(),这里“虚函数的动态绑定机制也没有会生效”,这是因为此时派生类已经不存在了

猜你喜欢

转载自blog.csdn.net/sinat_21107433/article/details/81836602