#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
Has compilation warning
Class '[C@1a9e0f7' has virtual method 'area' but non-virtual destructor
How to understand this warning and how to improve the code?
[EDIT] is this version correct now? (Trying to give answer to elucidate myself with the concept)
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual ~CPolygon(){};
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
~CRectangle(){}
};
It merely means that a code like
... or whatever wrapping into whatever smart pointer, will essentially not behave correctly since CPolygon is not polymorphic on deletion, and the CRectange part will not be destroyed properly.
If you're not going to delete CRectangle and CPolygon polymorphicaly, that warning is not meaningful.
it means you need a virtual destructor on a base class with virtual methods.
Leaving it off
iscan lead to undefined behavior, usually shows up as a memory leak in tools like valgrind.If a class has a virtual method, that means you want other classes to inherit from it. These classes could be destroyed through a base-class-reference or pointer, but this would only work if the base-class has a virtual destructor. If you have a class that is supposed to be usable polymorphically, it should also be deletable polymorphically.
This question is also answered in depth here. The following is a complete example program that demonstrates the effect:
Output:
Note that
delete bar;
causes both destructors,~Bar
and~BarBase
, to be called, whiledelete foo;
only calls~FooBase
. The latter is even undefined behavior, so that effect is not guaranteed.