0

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.

Abhishek Kumar
  • 729
  • 6
  • 20
  • [Policy based design and best practices - C++](https://stackoverflow.com/questions/872675/policy-based-design-and-best-practices-c), and [Use composition when you can, private inheritance when you have to.](https://stackoverflow.com/a/7209089/4123703) might be related. Policy inheritance does make inheritance semantically invalid. Composition is better, and using composition over private inheritance is better in my opinion. – Louis Go Jun 22 '20 at 01:47
  • Some choices are made because they are convenient and not necessary entirely correct. Balance between pro and cons. The "correct" solution might be too verbose, more "typo" possible, less clear intend, ... – Jarod42 Jun 22 '20 at 07:03

0 Answers0