Process pointers pointing to different structure types?

Hi!
Say I have n similar structures a1,a2,a3,a4,a5,...,an, derived from a base structure a,.
I need to create a function which automatically retrieves the value of one or more variables in all these structures, variables which have the same names since they are inherited from a. The problem is: how can I store the pointers to all those structures in a single bunch that would allow me to use a loop to process them? As far as I know, it is impossible to create a "general type" of pointer (array in this case) that would allow me to store addresses of different structures derived from the same base.

Thanks!
closed account (D80DSL3A)
Something like this?

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

#include<iostream>
using namespace std;

// base structure
struct a
{
	int x;
	a(int X){x = X;}
};

// derived structures
struct a1 : a
{
	a1(int X): a(X){}
};
struct a2 : a
{
	a2(int X): a(X){}
};
struct a3 : a
{
	a3(int X): a(X){}
};

int main(void)
{
	a  A(0);
	a1 A1(1);
	a2 A2(2);
	a3 A3(3);

       // create an array of pointers to base and initialize with addresses of base and derived types
	a* p_a[] = { &A, &A1, &A2, &A3 };

	for(int i=0; i<4; ++i)
		cout << " " << p_a[i]->x;// expecting 0 1 2 3 as output	

	cout << endl;
	return 0;	
}
Wow! That's exactely what I was looking for. I didn't know that an a* can point to instances of a1, a2 or a3.
Thanks!
Topic archived. No new replies allowed.