Example: Composition instead of public or private inheritance. What if you do need a
localized_string that is "almost like
string , but with some more state and functions and some tweaks to existing
string functions," and many functions' implementations will be unchanged? Then implement it in terms of
string safely by using containment instead of inheritance (which prevents slicing and undefined polymorphic deletion), and add passthrough functions to make unchanged functions visible:
class localized_string { public:
// … provide passthroughs to string member function that we want to
// retain unchanged (e.g., define insert that calls impl_.insert) … void clear();
// mask/redefine clear() bool is_in_klingon() const;
// add functionality private: std::string impl_;
// … add extra state … };
Admittedly, it's tedious to have to write passthrough functions for the member functions you want to keep, but such an implementation is vastly better and safer than using public or nonpublic inheritance.