前言

虚函数执行速度要稍慢一些。为了实现多态性,每一个派生类中均要保存相应虚函数的入口地址表,函数的调用机制也是间接实现。所以多态性总是要付出一定代价,但通用性是一个更高的目标。

实验环境

Windows10 企业版

Visual Studio2017 15.8.1

C++——多态实现原理分析

引入虚函数后内存大小变

没有虚函数时类占用内存大小

#include<iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Create Base" << endl;
    }
     ~Base()
    {
        cout << "Free Base" << endl;
    }
public:
    void Show()
    {
        cout << "This is Base Show()" << endl;
    }
private:
    int x;
};

void main()
{
    cout << sizeof(Base) << endl;
    Base b;
}
View Code

相关文章: