删除Vtable后调用虚函数

时间:2015-05-31 02:35:29

标签: c++ virtual-functions

为什么会出现分段错误?似乎删除了虚拟表,然后用户尝试调用看起来很荒谬的函数。

class base
{
    char *basep;
    public:

    // deep copy exist in copy constructor

    virtual char * fun()
    {
        cout << "fun from drive";
        return basep;
    }
    virtual ~base()
    {
        if(basep) { delete basep; }
        char *temp = fun();
    }
};

class derive : public base
{
    char *derived;
    public:
    // deep copy exist in the copy constructor of derived also
    virtual char *fun()
    {
        cout << "fun from drive";
        return derived;
    }
    ~derive()
    {
        if(derived) { delete derived; }
    }
};

int main()
{
    base *obj = new base;
    delete obj;
}

0 个答案:

没有答案