Virtual Default Destructors in C++

前端 未结 4 1603
旧巷少年郎
旧巷少年郎 2020-12-24 08:02

I\'ve got a large set of inherited classes (criteria) which inherit from a base class (criterion). Here\'s criterion\'s code

class criterion
{
p         


        
相关标签:
4条回答
  • 2020-12-24 08:22

    Yes - the base class needs a virtual destructor, even if it's empty. If that is not done, then when something delete's a derived object through a base pointer/reference, the derived object's member objects will not get a chance to destroy themselves properly.

    Derived classes do not need to declare or define their own destructor unless they need something other than default destructor behavior.

    0 讨论(0)
  • 2020-12-24 08:22

    The recommendation is to insert:

    virtual ~criterion() {}
    

    Starting from C++11, you can use = default; instead of an empty body {}.

    This is to avoid problems with deleting from a base class' pointer. Otherwise you will leak memory as derived classes' destructors will not be called.

    criterion *c = new fastFilter();
    delete c; // leaks
    
    0 讨论(0)
  • 2020-12-24 08:29

    One small change from what others have already answered:

    Instead of

    virtual void ~criterion() = 0;
    

    the required version is:

        virtual ~criterion() {}  //Note: Removed void as destructors not allowed 
                                 //  a return type
    

    To know more about virtual destructor have a look at this link from FAQ When should my destructor be virtual?

    0 讨论(0)
  • 2020-12-24 08:37

    You don't need to make the destructor abstract, just give it a empty implementation:

    virtual ~criterion() { }
    

    This way you are not forced to implement it in every child class, but still each of them will have a (inherited) virtual destructor.

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