Methodological abstract class?
class Base
{
virtual void bePolymorphic() = 0; // Will never be used
};
class Derived : Base
{
virtual void bePolymorphic() override {}; // I have to do this in every derived class
};
This is a hack I used recently to make a Base
class abstract if it doesn't have any member functions.
Java has a keyword abstract
. Why not in C ++? Is there any other way to create an abstract class?
The classic approach to this * problem is to make the destructor pure virtual. You must of course implement it outside of the class:
// In the header file
class Base {
virtual ~Base() = 0;
};
// In the source file
Base::~Base() {
}
* This proposal comes from a single Scott Meyers book .
Not. There is no abstract specifier in C ++. The equivalent is to protect your constructor:
class Base
{
protected:
Base() {}
virtual ~Base() {}
}
Also, the C ++ equivalent for the Java interface is one in which all your methods are purely virtual like yours and the constructor is protected. Also note that it is a good idea to always make the destructor virtual in the base class. If a derived class needs a destructor and the parent is not virtual, the derived constructor will not be called.