Aug 12, 2013 at 3:23am UTC
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 Aug 12, 2013 at 3:29am UTC
Aug 12, 2013 at 3:29am UTC
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 Aug 12, 2013 at 3:35am UTC
Aug 12, 2013 at 3:29am UTC
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.
Aug 12, 2013 at 4:16am UTC
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.
Aug 12, 2013 at 8:11am UTC
Hmm.. yes, of course. For some reason I was thinking that the classes were mutually referential.
Aug 13, 2013 at 3:47am UTC
wow thanks stewbond thats neat instantiating your classes like that. i would have never thought of that in a million years.