parent function manipulating member of derived class

Apr 8, 2016 at 11:43am
Hi. I've been trying to solve this problem for many days, but I couldn't find a good solution or design pattern..

I have this inheritance hierarchy,

struct Base{...};
struct Derived1{...};
struct Derived2{...};

And then I have this inheritance hierarchy, where child classes have vector of different classes.

struct Child{
vector<Derived1*> x;
void common1(); ... void commonN();
};

struct Child2{
vector<Derived2*> x;
void common1(); ... void commonN();
void unique();
};

So there is this kind of relationship,

Base
Derived1 <--> Child1
Derived2 <--> Child2

Child1 and Child2 have many common functions (e.g. common1, ... commonN), but each class has its own unique functions too. These functions usually manipulate the vector x.

I attempted to put Child1 and Child2 under a parent class, so that I can put all common functions in the parent class. However, I confronted some obstacles such as:
1) If I create a parent class and have it contain all common functions, the common functions should have access to vector members of the derived classes. I don't think it is doable..

Overall, can you please give me any advice on what would be the best strategy to solve code duplication and inheritance problem??
Apr 8, 2016 at 12:36pm
you can use a template as base class, that accepts the vector element type and :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename elem>
struct Child
{
	std::vector<elem*> x;
	void common1(); 
	void commonN();
};

struct Child1 : Child<Derived1>
{
};

struct Child2 : Child<Derived2>
{
	void unique();
};
Apr 8, 2016 at 12:41pm
Exactly!
I just figured that template base class might be what I want to use.
Now I feel more comfortable cause you confirmed my guess. Thank you :)

Just out of curiosity, is this design have any particular name?
Topic archived. No new replies allowed.