Post Self
Post Self

Reputation: 1554

Methodless 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 the hack that I have been using recently to make Base an abstract class if it doesn't have any member functions.

In Java there is an abstract keyword. Why isn't there one in C++? Is there another way of making a class abstract?

Upvotes: 3

Views: 155

Answers (2)

Nathan
Nathan

Reputation: 575

No. There is no abstract specifier in C++. The equivalent is to make your constructor protected:

class Base
{
protected:
    Base() {}
    virtual ~Base() {}
}

In addition, the C++ equivalent of a Java interface is one in which all of your methods are pure virtual, as you have, and the constructor is protected. Also note that it's a good idea to always make the destructor virtual in a base class. If a derived class needs a destructor and the parent's destructor isn't virtual, the derived's constructor won't be called.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

The classic work-around to this problem* is to make destructor pure virtual. Of course you must implement it outside the class:

// In the header file
class Base {
    virtual ~Base() = 0;
};
// In the source file
Base::~Base() {
}

* This suggestion comes from one of Scott Meyers' books.

Upvotes: 8

Related Questions