Reputation: 4211
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
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
Reputation: 149155
There are in fact 2 questions in one:
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