PDA

View Full Version : virtual members



mickey
12th August 2006, 20:21
hi,
Could anyone explain me about this warning? (and how take out it) thanks


warning 'class Cri' has virtual functions but non-virtual destructor

jacek
12th August 2006, 21:17
Could anyone explain me about this warning?
Actually it should be explained in any book that covers C++ basics.


class A
{
public:
A() {}
virtual foo() {}
~A() {}
};

class B : public A
{
public:
B() {}
virtual foo() {}
~B() {}
};

...

A *ptr = new B();
ptr->foo(); // B::foo() will be called, since ptr is in fact B instance, not A
delete ptr; // only A::~A() will be called, because destructor isn't virtual, hence the object won't be destructed properly.


and how take out it
Just read the error message and it will tell you what you need.

Michiel
13th August 2006, 00:06
But it IS annoying that you still get the warning if you don't have a destructor at all. I often have to add an empty virtual destructor to avoid it.

jacek
13th August 2006, 00:35
if you don't have a destructor at all.
Then you have a default one, which isn't virtual.

Michiel
13th August 2006, 11:20
Oh, never mind. I was arguing that the default destructor is empty, so doesn't have to be called. But the problem is, of course, that the destructor of the subclass needs to be called. If you don't make the superclass one virtual, that one gets called instead, empty or not.:p

Still annoying, though. I'd be ok with making it default behaviour in the case of other virtual members.