dimanche 21 juin 2020

Private vs Public inheritance in implementing policy based composition in C++?

I have been reading C++ Design by A. Alexandrescu. Following is a snippet from the book where WidgetManager is a class which gets the policy CreationPolicy.

// Library code
template <class CreationPolicy>
class WidgetManager : public CreationPolicy
{
 ...
}; 

This could have been implemented with creationPolicy as a member variable but that would require forwarding functions like

T* create()
{
    creationPolicy.create();
}

whereas inheritance directly exposes the functionality implemented by the policy avoiding verbosity. But it also breaks Liskov Substitution principle, publicly inherited policy will always break subtyping principles since widget isn't-a policy. Based on my understanding, I'd rather inherit privately and expose the single functionality each policy controls by using CreationPolicy::create syntax.

Though I see publicly inheriting policies to be a common practice. I am still trying to understand idiomatic C++. Could someone explain to me why inheriting policies publicly is okay (despite breaking subtyping principles)?

Also, please feel free to correct any errors in my above analysis of different ways of implementing policies. There are many similar questions about policies/inheritance on StackOverflow, in fact my first two paragraphs consist of what I understood from those questions. But the specific point of using public inheritance for policies is not answered anywhere.

Aucun commentaire:

Enregistrer un commentaire