Reputation: 14039
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++?
Upvotes: 2
Views: 866
Reputation: 238311
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.
Upvotes: 1
Reputation: 119857
Interfaces exist so that old code could call new code. You write an interface which provides a function, say foo()
. I can write code that calls foo()
now, even though no implementation of foo()
exists yet. It will be able to call any future implementations of foo()
, written long after I'm retired to my villa on the Bahamas.
If you proclaim that all future descendants of your class will implement a default constructor,this information is useless to me. I cannot construct instances of a class that isn't written yet! What should I or anyone else who hasn't seen a descendant of your class do with your announcement?
If there is user A who wants to create a descendant of your class, and user B who wants to instantiate A's class, then let them decide between themselves how to do this best. You are not a party in their deal.
But wait a minute, I can kinda sorta construct instances of a class that hasn't been written yet! I need to write a template, construct an object inside, and someone will instantiate it with their class. But then I just can use the default constructor, and this use will force anyone who wants to instantiate my template to implement the default constructor.
Of course you cannot force anyone to instantiate your template. If users need it, they will implement the constructor you require. If they don't need your services, you better don't tell them what to do.
Upvotes: 0