I want to make an empty base class called "Node", and then have other classes derived from this such as "DecisionNode" and "Leaf." It makes sense to do this so I can take advantage of polymorphism to pass these different kinds of nodes to methods without knowing at compile time what will be passed to the method, but each of the derived classes do not share any state or methods.
I thought the best way to implement this, without creating an additional pure virtual method in the base class, which would add clutter, would be to make the constructor pure virtual. In the header file for the class, "Node.h" I therefore wrote:
class Node {
private:
virtual Node();
};
and in "Node.cpp" I wrote:
#include "Node.h"
virtual Node::Node() = 0;
This implementation prevents Node from ever being instantiated by another class, since the only constructor is private and uses the pure virtual specifier to indicate that the class is abstract. However, this gives the compiler errors:
Node.h:6:21: error: return type specification for constructor invalid
Node.h:6:21: error: constructors cannot be declared virtual [-fpermissive]
My question is: is there a neat way to make an empty abstract base class?
In C++, constructors cannot be
virtual
. To prevent anyone from instantiating your base class, give it a protected constructor, like this:It will not be abstract, but only derived classes will be able to create its instances.
C++ doesn't support virtual constructor.
Below code won't compile:
Yes, make destructor a pure virtual function, also provides destructor function definition
What you are trying to do is
So you make a virtual distructor as ** virtual ~Node() = 0;**
you can't make the constructor virtual. If no other pure virtual functions are needed you can make the destructor pure virtual:
Create a virtual destructor and also provide an "empty" implementation.
The other alternative is to make the constructor protected, as others have commented. See also this question for some differences between the two. protected constructor versus pure virtual destructor
Edit Make sure you document why you are using the pure virtual destructor. The code by itself is cryptic in this regard and does not make it clear to someone who doesn't know about this "trick".
Edit 2 Your constructor should be
protected
, notprivate
. You won't be able to inherit if your constructor isprivate
.Simply: