Search code examples
c++inheritance

why derive from a concrete class is a poor design


I was reading about NonVirtual Interface pattern: Herb Sutter is talking about why virtual function must be private in most of the case, protected in some case and never public.

But at the end of the article he write:

Don't derive from concrete classes. Or, as Scott Meyers puts it in Item 33 of More Effective C++,[8] "Make non-leaf classes abstract." (Admittedly, it can happen in practice - in code written by someone else, of course, not by you! - and in this one case you may have to have a public virtual destructor just to accommodate what's already a poor design. Better to refactor and fix the design, though, if you can.)

But I don't understand why this is a poor design


Solution

  • A problem with inheriting from a concrete type is that it creates some ambiguity as to whether code which specifies a certain type really wants an object of the specific concrete type, or wants an object of a type which behaves in the fashion that the concrete type behaves. This distinction is vital in C++, since there are many cases where operations which will work correctly on objects of a certain type will fail badly on objects of derived types. In Java and .NET, there are many fewer situations where one can use an object of a particular type, but could not use an object of a derived type. As such, inheriting from a concrete type isn't nearly as problematical. Even there, however, having sealed concrete classes which inherit from abstract classes, and using the abstract class types everywhere except in constructor invocations (which must use the concrete types) will make it easier to change parts of the class hierarchy without breaking code.