I have a question there: Why does DerivedClass
inherits from ParentClass
?
Do you need a polymorphic behavior, or do you want to reuse the implementation of ParentClass
?
Inheritance is often badly misused. Really.
Then there is the (typical) problem of having a container class, and how to expose its elements. Unfortunately the iterators are (despite all their goods) poorly supported by the language unlike the pointers they are supposed to emulate.
So, a reminder: Inheritance is a is-a relationship, for code reuse there is Composition.
Here you could perfectly write a template class that would play the part of the container and provide common methods.
Then, for the problem of exposition... you can write your own iterators, with the correct base-derived relationship, or you can opt to preselect a number of algorithms (sort
, foreach
, erase_if
) that would work with user-supplied predicates.
template <class Value>
class Container
{
public:
template <class Pred>
void sort(Pred iPred);
template <class Pred>
Pred foreach(Pred iPred); // maybe a const-version ?
template <class Pred>
size_t erase_if(Pred iPred); // returns the number of erased
private:
std::vector<Value> m_data;
};
Then, on to your classes:
class ParentClass
{
public:
virtual void foo() const;
private:
Container<ParentObj*> m_data;
};
class DerivedClass: public ParentClass
{
public:
virtual void foo() const;
private:
Container<DerivedObj*> m_data;
};
Try to separate polymorphism from code reuse, and the problem should get simpler.