Re: Choosing between public and private inheritance
On Apr 16, 7:25 am, "Dennis Jones" <djo...@nospam.com> wrote:
typedef MapTree<int, MySpecialType> map_tree_type;
class MySpecialTree : private map_tree_type
{
public:
typedef map_tree_type inherited;
typedef inherited::node_type node_type;
typedef map_tree_type::ChildIterator_t ChildIterator_t;
void AddChild( node_type *ParentNode,
const key_type key,
const mapped_type &Item )
{
inherited::AddChild( ParentNode, key, Item );
}
This definition can be replaced by
using inherited::AddChild;
};
Note that I've used private inheritance to model the
"implemented-in-terms-of" relationship between the classes, rather than
public inheritance modelling an "is-a" relationship.
Private inheritance seemed to make sense at the time, but as I begin to use
the MySpecialTree class, I often find myself needing to use methods that
exist at higher levels of the hierarchy, and the only way to do that with
private inheritance is to re-implement the methods in terms of the ancestor
class (see AddChild). The same goes for typedefs (see node_type and
ChildIterator_t). This seems like a big waste of time and effort . . . not
to mention the mess it makes from what seems like a lot of unncesssary
declarations.
So, here's my question: how do I decide whether to use public or private
inheritance? If I switch to public inheritance, all of the extra
declarations and method implementations can go away. On the other hand, I'm
not sure public inheritance is what I want either, since the derived class
interfaces may be different from those of their ancestors.
I wouldn't recommend using public inheritance because I tend to find
that some of the inherited functions aren't quite right for the
derived class, or require some translation of parameters. In theory
containment is considered the Right Way, but providing a forwarding
implementation of every function is, as you've noted, a pain in the
neck. I suggest using private inheritance and using declarations, as I
have done above. A single line for each name you want to inherit isn't
too much bother.
Yechezkel Mett
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]