0

My code looks like this:

#include <iostream>

struct Parent
{  
    ~Parent()
    {
        std::cout << "parent destructor called" << std::endl;
    }
};

struct Child : public Parent
{
    int a, b, c;
    
    ~Child()
    {
        std::cout << "child destructor called" << std::endl;
    }
};

int main(int argc, char** argv)
{
    Parent* p = new Child;
    delete p;
    return 0;
}

The output is:

parent destructor called

As you can see the destructors are non-virtual. As expected only the parent destructor is called. My child class only has primitive members of type int.

In this case, is it enough if the parent destructor is called? May memory leaks happen? Is it clean CPP?

zomega
  • 1,538
  • 8
  • 26
  • No, it is not enough, this is UB. – Quimby May 25 '22 at 07:12
  • If having a pointer to base class is going to be useful, you still need some virtual functions to access anything in the derived class. So also adding a virtual destructor doesn't add any cost to this. If you instead do `Child* p = new Child; delete p;` you are ok without virtual destructors. It is the delete derived through pointer to base that is the problem case. – BoP May 25 '22 at 07:38
  • @BoP If they don't really need the polymorphism here, they should probably rather [prefer composition over inheritance](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) (or maybe template metaprogramming). – moooeeeep May 25 '22 at 08:03
  • No, it is not enough. In your code, due to `Parent` having a non-virtual destructor, the `delete p` in `main()` gives undefined behaviour. Among other things, that means the behaviour you are observing (that the parent destructor is called) is not actually guaranteed in any way. It also means that another compiler (or, even, your current compiler when updated to a newer version after the next full moon) could do something completely different - and still be 100% correct, since undefined behaviour means that the standard permits *any* behaviour, whether that behaviour seems sane or not. – Peter May 25 '22 at 08:50

0 Answers0