Making a class abstract without any pure virtual methods
You can declare your base class as having a pure virtual destructor that you implement. Since a destructor is always provided by the compiler, the derived class won't be purely virtual, but the base class can't directly be instantiated. You should always declare a destructor as virtual anyway, so this will have no overhead.
class Base
{
public:
virtual ~Base() = 0;
virtual void SomeVirtualMethod();
};
inline Base::~Base()
{
}
class Derived : public Base
{
};
inline Base* createBase()
{
// return new Base; // <- This won't compile
return new Derived; // <- This does compile, Derived is not a pure virtual class !
}
Specify the constructor of the base as protected. This does mean that you cannot construct it directly, but forces inheritance. There is nothing that makes a developer inherit from that class aside from good documentation though!
Example:
struct Abstract {
protected:
Abstract() {}
};
struct Valid: public Abstract {
// No need to override anything.
};
int main() {
// Abstract a; // This line fails constructor is protected
Valid v; // This compiles fine.
}
You can declare a pure virtual destructor, but give it a definition. The class will be abstract, but any inheriting classes will not by default be abstract.
struct Abstract
{
virtual ~Abstract() = 0;
};
Abstract::~Abstract() {}
struct Valid: public Abstract
{
// Notice you don't need to actually overide the base
// classes pure virtual method as it has a default
};
int main()
{
// Abstract a; // This line fails to compile as Abstract is abstract
Valid v; // This compiles fine.
}
Why would you want the user to inherit, if he does not have to implement anything.
When the base class is needed to be able to put all the "eventhandlers" in a std::set. Then no one can create a class and put it in this set without subclassing your base class. Because the set will be defined as
std::set<MyBaseClass*> mySet;