Inheritance problem

I think the best way to understand the problem is to look at an example of the behaviour I would like to achieve (see below). Essentially, I would like to replace a member of an inherited class with a member of a class inherited from the class of the original member. Obviously, you can solve it using templates, but, in my case, I am not sure if this is the best approach. Does anyone have any ideas for workarounds?

I am really trying to achieve something similar to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A {
...
};

class B {
...
vector<A> Var;
...
};

class Aext: A{
...
};

class Bext: B {
...
vector<Aext> Var;
...
};//i.e. I would like class Bext to operate using the methods of B on A part and with additional Bext methods on the Aext part. 




Last edited on
OK. Looks like I found a solution myself. I have to use pointers to derived class and virtual methods.
For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

class A {
	public:
	int a;
	A(int& ca) {a=ca;}
	virtual int GetT(void){return 0;};
};

class B{
	public:
	boost::ptr_vector<A> Trajectory;
	void PushBackStatePoint(int& ca);
};

void B::PushBackStatePoint(int& ca) {
	Trajectory.push_back(new A(ca));
}

class Aext: public A {
	public:
	int t;
	Aext(int& ca, int& ct) : A(ca) {t=ct;}
	virtual int GetT(void) {return t;}
};

class Bext: public B {
	public:
	void PushBackStatePoint(int& ca, int &ct);
	int GetFirstElement(void){return Trajectory[0].GetT();}
};

void Bext::PushBackStatePoint(int& ca, int &ct) {
	Trajectory.push_back(new Aext(ca,ct));
	
}

int main(){
	
	Bext MyB;
	int a(5);
	int t(3);
	MyB.PushBackStatePoint(a,t);
	std::cout << MyB.GetFirstElement();
}
Last edited on
Topic archived. No new replies allowed.