r/cpp_questions • u/Pizza_Gullible • 2h ago
SOLVED Memory leak in a virtual destructor of an abstract base class
I have an abstract base class from which other classes are derived. It has a pure virtual method and a virtual destructor with an empty body:
class LibraryItem
{
protected:
int id;
std::string title;
std::string author;
int year;
int cost;
friend class BookEditor;
public:
// other methods...
virtual void Print() const = 0;
virtual ~LibraryItem() {}
};My teacher said that I have a memory leak here, but I don't understand why.
The destructor is virtual, so when an object of a derived class is deleted through a LibraryItem*, the derived destructor should be called first, and then the base destructor.
I have always written destructors this way and have never received any complaints.
Some other students told me that because I declared the destructor with an empty body:
virtual ~LibraryItem() {}because "it does NOTHING**"**. But I thought it does nothing EXCEPT destroy the fields automatically. None of the fields in LibraryItem are raw pointers that would need to be deleted manually, so I don't understand where exactly my mistake / memory leak is.
I have seen people suggest writing:
virtual ~LibraryItem() = default;I would be very grateful if someone could explain:
- whether an empty virtual destructor like
virtual ~LibraryItem() {}can itself cause a memory leak; - what the difference is between
virtual ~LibraryItem() {}andvirtual ~LibraryItem() = default;in this context.
I was looking for similar questions, but I couldn't figure it out on my own.