Fabian
Fabian

Reputation: 4211

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?

Upvotes: 1

Views: 2510

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

C++ does not have a concept of interface. There are concrete classes and abstract classes, nothing more. Abstract classes are allowed to have constructors, data members and everything else. The only thing needed to mark a class abstract is a single pure virtual member function.

Some people use the word "interface" to denote an abstract class without any data members or non-pure-virtual member functions. Other people use slightly different definitions. The exact definition has no significance whatsoever as far as the language is concerned. You can have data members and define a constructor and still call your class an interface, nobody's going to issue you a citation for that. Or you can just avoid the term altogether.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149155

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.

Upvotes: 4

Related Questions