#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布局怎么样?
答案 0 :(得分:2)
当t
未初始化时,您正在将l
分配给l
。