Search code examples
c++inheritancetypedef

Typedef for complicated base class


I am using private inheritance to model my has-a relationship, but my base class type is rather complicated (well, a little bit), and I would like to have a typedef for it. Is something like the following possible in C++

struct S : private typedef std::vector<int> Container {};

Currently I am doing:

template< typename Container = std::vector<int> >
struct S : private Container {};

But this

  • makes my class to a template class. This is not a big problem for my current application (since it is a template class anyway), but in general is not nice.
  • could lead to bugs, when people think they are allowed to specify their own container.

Solution

  • Considering that:

    you could prefer private composition:

    struct S {
      using Container = std::vector<int>; // outside struct also possible
      private: Container container;  
    };  
    

    There is no code duplication here: with inheritance, you'd just have a container sub-object whereas with composition you'd have a container member, and both would use the same code.

    There is no decisive advantage of private inheritance, since other classes could not use the public members defined in the base class. The only advantage is that you can use public members in the class definition, whereas with composition, you'll have to prefix the member with the object name.