Search code examples
c++constructorinterfaceabstract-classpure-virtual

Can I enforce defining a specific constructor with an interface class?


I want to create an interface - an abstract class, which among others enforces derived classes (i.e. conforming to the interface) to provide a specific constructor.

Something along the lines:

class IComClient
{
public:
    virtual IComClient(int _id, TBaseCom*_com) = 0;
    virtual void task() = 0;
private:
    int id;
    TBaseCom* com;
);

Obviously, that won't work - as I read, a class can't have a pure virtual constructor - or a virtual constructor in general. I don't care about creating instances of derived classes in a polymorphic manner, I just want the compiler to protest if the derived class doesn't provide a constructor that takes these specific input parameters.

There's an answer for C# but is the situation the same in C++?


Solution

  • There is no way to enforce the existence of a specific constructor for derived classes in the base class.

    You can enforce the existence of a specific constructor by attempting to invoke that constructor, or using static_assert.

    Something similar might be achievable not by a base class, but using a meta class... if they are accepted into the language in a future standard.