Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructor in C++

Tags:

c++

I had a constructor in my AB.h file:

class AB{
private: int i;
public:
AB:i(0){}//constructor
~AB:i(0){} // destructor
virtual void methodA(unsigned int value)=0;};

The compiler said that:

class AB has virtual functions but non-virtual destructor
AB.h: In destructor ‘AB::~AB()’:
AC.h: error: only constructors take base initializers

if I use the ~AB(); destructor, it said that i have virtual functions but i didn't have destructor, where did I misunderstand? Thankyou

like image 611
Xitrum Avatar asked Nov 30 '22 04:11

Xitrum


1 Answers

Using an initialization list such as

AB : a_member(4),another_member(5) {}

makes only sense (and is permitted) for constructors - in a destructor, you don't want to initialize things.

In addition to this obvious syntax error, the compiler warns because AB has a virtual method but doesn't declare it's destructor virtual as well. This is recommended because of the following:

AB* ab = new SomethingDerivedFromAB();
delete ab; // calls only AB's dtor and not SomethingDeriveFromAB's unless AB declares its dtor virtual
like image 120
Alexander Gessler Avatar answered Dec 05 '22 13:12

Alexander Gessler