Search code examples
c++abstract-base-class

Can I define a constructor in an abstract base class?


I want to write an "interface" class in C++, which is a purely virtual abstract base class.

Can I define the constructors in this interface class? A constructor cannot be a purely virtual function, but how can I then define constructors for the interface class?

Edit: Do I need a virtual destructor in such an interface class?


Solution

  • There are in fact 2 questions in one:

    • Can an ABC have a ctor?: Of course it can! Imagine you have an almost complete class, with private data and that only lacks one concrete method. This method should be pure virtual making the class abstract, but you still have to initialize class data in a ctor. The question suggested by Paul Rooney is an example for that
    • Can an interface have a ctor?: No, it cannot by definition. An interface is a special ABC that only contains pure virtual methods. It has no implementation not even a partial one, and as such needs no ctor. And you already noted that

    A constructor cannot be a purely virtual function

    TL/DR: if you are trying to add a constructor to your interface, then it is no longer an interface but a simple Abstract Base Class that is perfectly allowed to have one.