继承层次结构中间类的新虚函数

时间:2016-03-17 18:00:58

标签: c++ oop

#include <iostream>
using namespace std;

class top {
    public:
        virtual void foo(void) {cout << "I am top foo\n";}
};
class middle : public top {
    public:
        virtual void foo(void) {cout << "I am middle foo\n";}
        virtual void bar(void) {cout << "I am middle bar\n";}
};
class lower : public middle {
    public:
        virtual void foo(void) {cout << "I am lower foo\n";}
        virtual void bar(void) {cout << "I am lower bar\n";}
};
int main() {
    top *t = new top();
    middle *m = new middle();
    lower *l;
    t = m;
    t->foo(); // works fine
    t = l;
    t->foo(); // causes segmentation fault/ undefined behavior
    l->foo(); // works fine if above is commented

    return 0;
}

我知道这里已经回答了类似的查询,但我想从vtable布局的角度来看这个问题。如果vtable布局不同,是否不允许调用中间类虚函数调用?在这里,我看到虚拟bar()被定义为中产阶级。每个类的vtable布局怎么样?

1 个答案:

答案 0 :(得分:2)

t未初始化时,您正在将l分配给l