Problem with STL and Composition

I am writing a code which is similar to the below module.
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
45
46
47
class testclass5;	//Forward Declarations
class testclass4;
class testclass3;
class testclass2;

class testclass1
{
public:	int a;
	int b;
	list<testclass2> listobj2;
};

class testclass2
{
public:
	testclass3 obj3;   #Should i declare them as obj3()
	testclass4 obj4;
	int qwe;
};

class testclass3
{
public:
	int p;
	int q;
	testclass3()
	{
	p=4;q=5;
	}
};

class testclass4
{
public:
	int k;	
	list<testclass5> listobj5;
	testclass4()
	{
	k=10;
	}
};

class testclass5
{
public:
	int x;
};

1
2
3
4
5
6
7
8
9
10
11
testclass1 obj1;
testclass2 obj2[10];
	for (int i=0;i<10;i++)
	{
		obj1.listobj2.push_back(obj2[i]);	
	}
int data=rand()%100;
testclass5 obj5;
obj5.x=10;
obj1.listobj2.front().obj4.listobj5.push_back(obj5);
return 0;

The code isn't recognising obj3 and obj4 as members of testclass2.

list3_test.cpp:57:13: error: field ‘obj3’ has incomplete type
list3_test.cpp:58:13: error: field ‘obj4’ has incomplete type
list3_test.cpp: In function ‘int main()’:
list3_test.cpp:110:25: error: ‘class testclass2’ has no member named ‘obj4’

Please Help.
Also read my comment in testclass2.
Forward declaration works for references and pointers.
If you want an object, you need to provide the class definition before.
Thanx for the info. Its working now. But if i add some extra code again same error is coming.
Extra code:
1
2
3
4
5
6
7
8
9
10
list<testclass2>::iterator it;
	testclass5 obj5[10];
	int i=0;
	for ( it=obj1.listobj2.begin() ; it != obj1.listobj2.end(); it++ )
	{
		int data=rand()%100;
		obj5[i].x=data;		
		obj1.*it.obj4.listobj5.push_back(obj5[i]);
		i++;
	}

The error is:

list3_test.cpp: In function ‘int main()’:
list3_test.cpp:112:12: error: ‘std::list<testclass2>::iterator’ has no member named ‘obj4’
Yuck, look at Demeter's Law.


About your error
for ( it=obj1.listobj2.begin() ;here you are associating an iterator to a list. Now you've got direct access to that list, if you dereference the iterator you've got an object of that list.
So it makes no sense to say obj1.*it
Last edited on
Its working now. thanks for the help :)
Topic archived. No new replies allowed.