0

Do I need virtual destructor when I am using boost::ublas matrix ?

By the way, my class is a template class.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Ismail Marmoush
  • 13,140
  • 25
  • 80
  • 114

1 Answers1

1

Do you mean you have this?

template <typename Whatever>
struct my_class
{
    // ...

    boost::ublas::matrix m;
};

There's nothing here that dictates you have a virtual destructor.


You want a virtual destructor when you intend on having users publically derive from your class. So that question should be "Users will publically derive from my class, do I need a virtual destructor?". Yes, you do.

The reason is that doing this leads to undefined behavior:

struct base {}; // no virtual destructor
struct derived : base {};

base* b = new derived;

// undefined behavior, dynamic type does not match static type,
// and the base class does not have a virtual destructor
delete b; 

This does not:

struct base { virtual ~base(){} }; // virtual destructor
struct derived : base {};

base* b = new derived;

// well-defined behavior, dynamic type does not match static type,
// but the base class has a virtual destructor
delete b; 

Note that it has nothing to do with what members there are in the base class. You always need a virtual destructor if users will be deleting derived classes through a pointer to a base class.


I would recommend you get a book so you know what it does, because it sounds like you just throw things around and hope it works, which isn't a very good approach.

Community
  • 1
  • 1
GManNickG
  • 494,350
  • 52
  • 494
  • 543