fluffy_muffin fluffy_muffin - 10 months ago 46
C++ Question

destructor and no constructor for abstract base class c++

I searched for this, but I didn't really understand the answers.

I am completely new to C++, and what I am trying to achieve is to have an abstract class which serves as a base class for my object types so that I can store my objects in an array of pointers of type of the abstract class instead of using

void *
. Moreover, my objects share a few common member functions which could easily reduce my code base with the abstract class implementation.

However, I am confused about the constructor and destructor for the abstract class.

The abstract class doesn't really need a constructor since the parameters that could be passed in that are common to both require different things to be done with said parameter in the derived class to set the protected attributes correctly (sizing of a matrix). So, is it okay to not have a constructor? Also, since I don't have a constructor what should the destructor be?

I say an answer where it was to implement a virtual destructor. However, I'm not sure what this means and there was a discussion about potential memory leaks saying there wouldn't be any as long as the derived classes reimplemented the destructor. So, this does mean that I can implement a virtual decstructor and then in the derived objects say
I simply implement
to prevent memory leaks (assuming they're correct of course)? I wasn't confident I understood what the re-implementation in the derived classes meant exactly.

Answer Source

In general abstract classes in c++ should provide a virtual destructor definition. This can be made abstract also

 virtual ~MyClass() = 0;

 // Define a body in any case
 MyClass::~MyClass() {}

An abstract class doesn't need to declare a constructor (Which can't be a pure virtual function BTW).

A constructor may make sense, when your abstract class isn't a plain interface (no data members).