I’ve a medium chunk of code containing 5 classes that they’re all inherited from standard containers. For example:
class Step : public std::vector<unsigned int>
{
public:
friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
Step& operator =(const Step& rhv);
static Step fromString(const std::string &input);
std::string name;
};
I know it’s a bad idea to inherit from standard containers, so I’m going to remove all inheritances by adding a subobject of parent datatype:
class Step
{
public:
friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
Step& operator =(const Step& rhv);
static Step fromString(const std::string &input);
std::string name;
// std::vector interface:
inline std::vector<unsigned int>::const_iterator begin() const {return data.begin();}
inline std::vector<unsigned int>::const_iterator end() const {return data.end();}
inline size_t size() const {return data.size();}
typedef std::vector<unsigned int>::const_iterator const_iterator;
private:
std::vector<unsigned int> data;
};
I’m doing this because the code is widely used in other programs and changing structure is very costly.
And question: what do you suggest to revise the code by small changes? (as less as possible)
Clarification:
I have a some classes inherited from stl containers. And there are lots of codes using them. My question is that how do I remove that evil inheritance without changing codes using those classes?
One potential solution: making the inheritance private (or protected, if it makes sense), and
usingthe relevant members:If inheritance indeed made the code simpler, then you may like this solution. The real problem with inheriting from containers is that the conversion to
vectormay get you in trouble once you add members to theStepclass: the destructor changes, and you know, it’s not virtual in the first place. Private inheritance solves this problem.