C++之构造函数为什么不能为虚函数

针对虚函数在说虚函数表的时候已经说过了 C++之虚函数表,虚函数的运行是根据虚函数表,而虚函数表是在对象生成后,释放前才存在的,构造函数就是来生成对象的,对象还没有生成,就把构造函数声明为了虚函数,放到了虚函数表中,可是虚函数表又不存在,这就矛盾了,故当然不可以把构造函数声明为虚函数,如果这么做了,编译器直接报错。

举几个例子实实在在的展示一下虚函数表的生命周期:

public:
    Father() {
        this->func();
    }
    ~Father() {}

    virtual void func() {
        cout << "Father::fun()" << endl;
    }
};

class Son : public Father {
public:
    Son() {
    }
    ~Son() {}

    virtual void func() {
        cout << "Son::fun()" << endl;
    }
};

int main() {
    Son s;
    system("pause");
    return 0;
}

输出结果:

这里写图片描述

这里Father的构造函数中的this指针是Father类的对象,调用func()函数并没有实现多态,正式因为此时Son类对象还没有创建,此时的虚函数表不存在。

再举个例子:

#include<iostream>

using namespace std;

class Father {
public:
    Father() {

    }
    ~Father() {
        this->func();
    }

    virtual void func() {
        cout << "Father::fun()" << endl;
    }
};

class Son : public Father {
public:
    Son() {
    }
    ~Son() {}

    virtual void func() {
        cout << "Son::fun()" << endl;
    }
};

int main() {
    Son s;
    system("pause");
    return 0;
}

输出结果:

这里写图片描述

Father的析构函数有个this指针,仍然指向Father的对象,调用了func()函数,仍然没有实现多态,因为Father析构的时候,子类Son已经析构掉了,此时虚函数表也已经不存在了,自然也无法实现多态。

再来看一个:

#include<iostream>

using namespace std;

class Father {
public:
    Father() {

    }
    ~Father() {
        this->func();
    }

    virtual void func() {
        cout << "Father::fun()" << endl;
    }

    void foo(){
        this->func();
    }
};

class Son : public Father {
public:
    Son() {
    }
    ~Son() {}

    virtual void func() {
        cout << "Son::fun()" << endl;
    }
};

int main() {
    Son s;
    s.foo();
    system("pause");
    return 0;
}

输出结果:

这里写图片描述

这个时候就完美的实现了多态,此时Son对象已经生成,也没有被析构,虚函数表是存在的,这就为实现多态奠定了坚实的基础。

从上面三个例子就能看出虚函数表的生命周期是完全依赖于对象的声明周期的,对象存在虚函数表存在,对象不存在虚函数表也不存在。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值