Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default virtual d'tor

Tags:

c++

destructor

Let us assume I have two classes:

class Base{};

class Derived: public Base{};

none has d'tor, in this case if I declare about variables:

Base b;
Derived d;

my compiler will produce for me d'tors, my question is, the default d'tors of the b and d will be virtual or not?

like image 230
rookie Avatar asked Oct 10 '10 09:10

rookie


2 Answers

The destructors of Base and Derived will not be virtual. To make a virtual destructor you need to mark it up explicitly:

struct Base
{
    virtual ~Base() {}
};

Actually there's now only one reason to use virtual destructors. That is to shut up the gcc warning: "class 'Base' has virtual functions but non-virtual destructor". As long as you always store your allocated objects in a shared_ptr, then you really don't need a virtual destructor. Here's how:

#include <iostream>   // cout, endl
#include <memory>     // shared_ptr
#include <string>     // string

struct Base
{
   virtual std::string GetName() const = 0;
};

class Concrete : public Base
{
   std::string GetName() const
   {
      return "Concrete";
   }
};

int main()
{
   std::shared_ptr<Base> b(new Concrete);
   std::cout << b->GetName() << std::endl;
}

The shared_ptr will clean up correctly, without the need for a virtual destructor. Remember, you will need to use the shared_ptr though!

Good luck!

like image 191
Daniel Lidström Avatar answered Oct 13 '22 00:10

Daniel Lidström


my question is, the d'tors of the b and d will be virtual or not

No, they won't. If you want a virtual destructor, you will have to define your own, even if its implementation is exactly the same as that which would be supplied by the compiler:

class Base {
  public:
    virtual ~Base() {}
};
like image 40
sbi Avatar answered Oct 13 '22 00:10

sbi