Destructing derived class by deleting base class

后端 未结 3 388
暗喜
暗喜 2021-01-25 16:39

I have a situation that looks like the following code:

#include 

class A
{
public:
    A() { std::cout << \"A created!\" << std::end         


        
相关标签:
3条回答
  • 2021-01-25 17:07

    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.

    0 讨论(0)
  • 2021-01-25 17:09

    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.

    0 讨论(0)
  • 2021-01-25 17:30

    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.

    0 讨论(0)
提交回复
热议问题