Refer to another class

Hello

I'm encountering the following problem in my code:
1. I have two classes (A & B )/>/>, each having one function ( X() & Y() ).
2. Now, I need to enter function Y(), from X(). => Error.

Code:
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>
using namespace std;

//Tried but failed
class A;
class B;

class A {
public:
	B B;
	void x() {
		//How to call?
		if(B.y()) {
			cout << "Function Y returned 'true'" << endl;
		}
	}
};

class B {
public:
	bool y() {
		if(5 < 2) {
			return true;
		}
		else return false;
	}
};

int main() {
	A A;
	A.x();

	return 0;
}


Errors:

Code Description Line
C2079 'A::B' uses undefined class 'B' 10
C2228 left of '.y' must have class/struct/union 12



I tried forwarding, but that ain't working very well.
Other's are talking about creating a new header file, but I personally guess that's a bit of an overkill for this problem.

How to do this?

Thanks!
Your B does not depend on A and thus it can be defined before the A:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Foo {
public:
  bool y() { return true; }
};

class Bar {
  Foo foo;
public:
  bool x() { return foo.y(); }
};

int main() {
  Bar boo;
  boo.x();
  return 0;
}
In my real code it does. This was just an example.
The solution is within a question: Who needs what?
Now, your incomplete example does not allow us to ponder that question thoroughly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Foo {
public:
  bool y();
}; // definition of Foo does not require Bar

class Bar {
  Foo foo;
public:
  bool x() { return foo.y(); }
};

int main() {
  Bar boo;
  boo.x();
  return 0;
}

// implementation of Foo::y does have to know the definition of Bar
bool Foo::y() {
  return 4 < sizeof(Bar);
}
Topic archived. No new replies allowed.