left of '.i' must have class/struct/union?

Why does the following code not work? I know its a problem with scope i just dont know how to fix it.

This complication arose in a much more complected program that i was working on so i made a new simpler program solely for the purpose of demonstrating the problem that I'm having.

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
#include <iostream>

class COne
{
public:
	void f() {
		std::cout << qTwo.i;
	}
};

class CTwo
{
public:
	CTwo() {
		i=1;
	}
	int i;
};

COne qOne;
CTwo qTwo;

int main() {
	qOne.f();
	system("pause");
}


im going to bed now so ill check the replies in the morning. you wonderful people always come through so ill go ahead and say thanks in advance!
Last edited on
closed account (N36fSL3A)
Try 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
#include <iostream>

class COne;
class CTwo;

class COne
{
public:
	void f(CTwo qTwo) ;
};

class CTwo
{
public:
        CTwo();
	int i;
};

CTwo::CTwo() {
	i=1;
}

void COne::f(CTwo qTwo) {
	std::cout << qTwo.i;
}

CTwo qTwo;
COne qOne;

int main() {
	qOne.f(qTwo);
	system("pause");
}


You're trying to access an object that's not even defined.

(Tell me if this doesn't work, I'm very tired right now)
Last edited on
Line 7, qTwo is not in that scope, so the object doesn't exist there. The compiler doesn't know what qTwo.i is.
qTwo is instantiated later in the code.
The only way to do it is to separate the method bodies from the class definitions/type/whatever.

class QOne;
class QTwo;

class QOne
{
Void f( QTwo qTwo );
}

Class QTwo
{
...
}

Void QOne::f( QTwo qTwo )
{
Cout << qTwo.i;
}

If QOne is going to access private stuff in QTwo, you'll have to declare it a friend, too.

Hope this helps.
Here's another way that may help. Define CTwo and qTwo before COne.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class CTwo
{
public:
	CTwo() {
		i=1;
	}
	int i;
}qTwo;

class COne
{
public:
	void f() {
		std::cout << qTwo.i;
	}
}qOne;

int main() {
	qOne.f();
	system("pause");
}
Hmm.. yes, of course. For some reason I was thinking that the classes were mutually referential.
wow thanks stewbond thats neat instantiating your classes like that. i would have never thought of that in a million years.
Topic archived. No new replies allowed.