I have a question: why does DerivedClass inherit from ParentClass ?
Do you need polymorphic behavior or want to reuse the ParentClass implementation?
Inheritance is often poorly used. Actually.
Then there is a (typical) problem of having a container class and how to display its elements. Unfortunately, iterators (despite all their products) are poorly supported by the language, unlike pointers, which they must imitate.
So, a reminder: Inheritance is is-a , there is Composition for code reuse.
Here you can write a great class of templates that will play the role of a container and provide common methods.
Then, for the presentation task ... you can write your own iterators with the right base-dependent relationship, or you can select the preliminary selection of several algorithms ( sort , foreach , erase_if ) that will work with predicates provided by the user.
template <class Value> class Container { public: template <class Pred> void sort(Pred iPred); template <class Pred> Pred foreach(Pred iPred);
Then 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 be simpler.
source share