circular references

http://www.cplusplus.com/forum/beginner/2829/
http://www.cplusplus.com/forum/beginner/6075/

I have a question about forward references. Do forward/circular references ever work with anything OTHER than a pointer? I'm guessing even with forward reference, you cannot use the object itself because it is not defined yet, so you can only use a pointer to it? Therefore you cannot invoke the external object's constructor or put it in the initializer list. Is there any excepton to this? On some other C++ sites someone mentioned this was being considered as a possible change in C++0x?

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
48
49
50
51
52
53
54
55
#include <iostream>

using namespace std;

class myClass2;

int recursionLevel = 0;

class myClass1
{
public:
	//myClass2 mc2;						//must be pointer, cannot use: myClass2 mc2;
	myClass2 *mc2;  
	void myClass2_ctor(int);
	myClass1(int inVal) : myInt1(inVal) //, mc2(inVal) cannot put in initializer list  
	{ 
		cout << "ctor for myClass1 ";
		//mc2 = new myClass2(inVal);	//cannot yet use constructor for mc2
		myClass2_ctor(++inVal);			//must initialize mc2 in external func 
	}
	int myInt1;
};

class myClass2
{
public:
	//myClass2 mc1;						//must be pointer, cannot use: myClass1 mc1;
	myClass1 *mc1;  
	void myClass1_ctor(int);
	myClass2(int inVal) : myInt1(inVal) //, mc1(inVal) cannot put in initializer list 
	{ 
		cout << "ctor for myClass2 ";
		//mc1 = new myClass1(inVal);	//cannot yet use constructor for mc1
		myClass1_ctor(++inVal);			//must initialize mc1 in external func  
	}
	int myInt1;
};

//circular reference limited by recursion level
void myClass1::myClass2_ctor(int inVal){
	if (inVal < 30) {
		cout << "new class2 for class1 " << inVal << endl; 
		mc2 = new myClass2(inVal); }
}
void myClass2::myClass1_ctor(int inVal){
	if (inVal < 30) {
		cout << "new class1 for class2 " << inVal << endl; 
		mc1 = new myClass1(inVal); }
}

int main()
{
	myClass1 mc1(1);
	return 0;
}


http://www.cplusplus.com/forum/articles/10627/

Check sections 4 and up.

Specifically 6 and 7

A class that was only forward declared can only be used as a pointer/reference, and that pointer reference cannot be dereferenced until the class is fully defined.

However this does not prevent you from having circular dependencies, as you can always work around these types of problems with good design. See the "right way" method I outline in that article.
Excellent article, thank you Disch.
Topic archived. No new replies allowed.