Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "Virtual functions but no virtual destructors"

Tags:

c++

I have a base class Media and several derived classes, namely DVD, Book, etc... The base class is written as:

class Media{     private:         int id;         string title;         int year;     public:         Media(){ id = year = 0; title = ""; }         Media(int _id, string _title, int _year): id(_id), title(_title), year(_year) {} //      virtual ~Media() = 0;         void changeID(int newID){ id = newID; }         virtual void print(ostream &out); }; 

The thing is: without the destructor, GCC gives me a bunch of warnings class has virtual functions but non-virtual destructor, but still compiles and my program works fine. Now I want to get rid of those annoying warnings so I satisfy the compiler by adding a virtual destructor, the result is: it doesn't compile, with the error:

undefined reference to `Media::~Media()` 

Making the destructor pure virtual doesn't solve the problem. So what has gone wrong?

like image 837
Max Avatar asked Apr 05 '12 08:04

Max


People also ask

Which has virtual members does not have a virtual destructor?

A C++ class containing virtual member functions has a non-virtual destructor. Since this class has virtual member functions, it will be used as a base class.

Do I always need a virtual destructor?

Declaring a destructor virtual is only necessary when you plan to make your class inheritable. Usually the classes of the standard library (such as std::string ) do not provide a virtual destructor and thus are not meant for subclassing. The reason is subclassing + use of polymorphism.

What happens if destructor is not virtual?

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior.

Why we can not have a virtual constructor but we can have a virtual destructor?

Virtual Constructor in C++ In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual. But virtual destructor is possible.


1 Answers

You need to also define the virtual destructor, not only add it.

//Media.h class Media{     //....     virtual ~Media() = 0; };  //Media.cpp #include "Media.h" //.... Media::~Media() {}; 

The reason you get the warnings is that all classes that will be derived from should have a virtual or protected (credit @Steve) destructor, otherwise deleting an instance via a pointer to a base class results in undefined behavior.

Note you HAVE TO provide a definition for destructors, even if they are pure virtual.

like image 137
Luchian Grigore Avatar answered Sep 20 '22 07:09

Luchian Grigore