C++虚函数与C++虚函数表

这个问题被勾起来的原因是听到师兄面试又被提到。本来知道这玩意,但还是想实践检验一下加深理解。

1)上酸菜:

  类是创建对象的模子!

#include <iostream>
using namespace std;

class root
{
protected:
    int id;
public:
    root()
    {
        id = 1;
    }
    virtual void say()
    {
        cout << "i am the root" << endl;
    }
    virtual void move()
    {
        cout << "i can move here and there" << endl;
    }
};

class leaf: public root
{
protected:
    int color;
public:
    leaf()
    {
        id = 2;
        color = 999;
    }
    void say()
    {
        cout << "I am the leaf" << endl;
    }
};
int main(int argc, char* argv[])
{
    root r;
    r.say();

    leaf l;
    l.say();

    root* p;
    p = new leaf();
    //p->say();
    //p->move();

    return 0;
}

2)调试跟踪:

watch的皆是数据对象。(内存中包括数据和代码)

  可以看到:

    1)r的id之前一个__vfptr(虚函数表指针)。

    2)l的color之前是一个root。注意其中的__vfptr[0]已经变成leaf::say(void)。

  于是有下图,注意到l中包含一个root。

对于p和*p有:

  可以看到:

    0)标出的内容值都是一样。

    1)p有两种解释,一个leaf或者一个虚函数表。

    2)*p只有一种数据对象解释:一个root。

      a)注意到源代码中定义为root* p。b)注意下面没有了color。

  于是有下图:

原文地址:https://www.cnblogs.com/jiejue/p/2751924.html