The snippet below will coredumped in fun()
method. Why calling c->b.f()
works in main()
but failed in the function call?
class A {
public:
inline virtual void f() const {printf("A\n");}
};
class B : public A {
public:
inline void f() const override {printf("B\n");}
};
class C {
public:
B b;
};
void fun(const B &b) {
b.f(); // coredump
}
int main() {
C *c = (C*)malloc(sizeof(C));
c->b.f(); // print "B"
fun(c->b);
return 0;
}
I guess it's because the virtual table is not initialized properly.