Destructing derived class by deleting base class

只愿长相守 提交于 2020-07-03 10:17:11

问题


I have a situation that looks like the following code:

#include <iostream>

class A
{
public:
    A() { std::cout << "A created!" << std::endl; }
    ~A() { std::cout << "A destroyed!" << std::endl; }

    virtual const char* Name() { return "A"; }
};

class B : public A
{
public:
    B() { std::cout << "B created!" << std::endl; }
    ~B() { std::cout << "B destroyed!" << std::endl; }

    const char* Name() { return "B"; }
};

int main()
{
    A* a = new B();

    std::cout << a->Name() << "\n";

    delete a;

    return 0;
}

I want B to be destroyed when A is destroyed too. Is this possible in its destructor or do I have to implement a virtual Destroy() method or something like that?


回答1:


As a rule of thumb, if any of your methods are virtual, the destructor must also be virtual. If it isn't, the declared type of a variable decides which destructor gets called, which is almost never what you want. 99.9% of all cases, you want the destructor from the runtime type.




回答2:


Is this possible in its destructor or do I have to implement a virtual Destroy() method or something like that?

Make destructor of A virtual.

 virtual ~A() { std::cout << "A destroyed!" << std::endl; }

If your class have virtual methods, it should use virtual destructor. At least some compilers will complain if you aren't using virtual destructor in class with virtual methods.




回答3:


If you apply operator "delete" to base class pointer, destructor MUST be virtual (existence of other virtual methods does not matter). For instance, in case of multiple inheritance "delete" operator applied to base class pointer will cause memory fault since compiler doesn't even know were the memory occupied by derived object begins.



来源:https://stackoverflow.com/questions/3378442/destructing-derived-class-by-deleting-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!