In C++ Inheritance, Derived class destructor not called when pointer object to base class is pointed to derived class

前端 未结 2 1013
别那么骄傲
别那么骄傲 2020-12-07 02:25

I am a newbie and I know this is a very basic concept and might be a duplicate too. Is it not true that once a constructor is called its corresponding destructor has to be c

相关标签:
2条回答
  • 2020-12-07 03:17

    There is no need to call a destructor if it is trivial.

    That does not help in your example though, because if a class has a sub-object with non-trivial destructor (member or base) or its own destructor is user-defined, it is not trivial.

    Also, you may only delete a class using a pointer to base, if that base-class has a virtual destructor, on pain of undefined behavior (The compiler need not warn you).

    Pro-tip: If you need to make it virtual (for example due to above requirement), but do not want to prevent it from being trivial (some containers and algorithms have optimized implementations for trivial types), use:

    virtual ~MyClass = default; // Since C++11
    

    So, never delete using a pointer to Base if Base does not have a virtual destructor or it is actually really a base.

    0 讨论(0)
  • 2020-12-07 03:20

    Your code has undefined behavior. The base class's destructor must be virtual for the following to have defined behavior.

    Base* b = new Derived;    
    delete b;
    

    From the C++ standard:

    5.3.5 Delete

    3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

    So in your case, the static type is Base, and the dynamic type is Derived. So the Base's destructor should be:

    virtual ~Base() {cout << "Base Destructor\n"; }
    
    0 讨论(0)
提交回复
热议问题