I have a C++ class that implements reference-counting and I want all users of this class to inherit from this class only virtually so that no object ends up with more than one reference counter.
I’d like some way to assert this requirment either during compile time or at least during runtime.
Is there a way to achieve that?
I think wrapping the class would be the simplest option. Rather than directly inheriting from RefCounter create an intermediary class.
Then everything can inherit from
RefCounterwithout any need to care about virtual inheritence. You don’t even have to change any existing code — virtual inheritence ofRefCounteritself should be harmless.This of course doesn’t guarantee people don’t inherit from
RefCounterVirtPrivate_directly, but that is why I’ve given it an obvious name. It’s harder to accidentally do this than forget avirtualkeyword.