views:

36

answers:

1

do i need virtual destructor when iam using boost::ublas matrix ? btw my class is a template class

+1  A: 

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.

GMan
yes @ first question tht's what my class look like , and yes I intent to have users derive from my class . really thanks alot :)
ismail marmoush
@ismail: Oh, then to clarify: you do need `virtual`.
GMan
@GMan yes indeed :D
ismail marmoush