a problem of mutual type reference

I met a problem which has been simplified as follows.
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef A_H
#define A_H

#include "B.h"

class A {
public:
	struct C {
	};
	B b;
}; 
#endif 

1
2
3
4
5
6
7
8
9
10
#ifndef B_H
#define B_H

#include "A.h"

class B {
public:
	void func(A::C & c) {} ;
};
#endif  

1
2
3
4
5
6
7
#include "A.h"
#include "B.h"

int main()
{
	A a; B b;
} 

The source was compiled with errors. I find the problem can't be solved until the mutual type reference is avoided in the code. I wonder if there is there any solution to this situation. Thanks!
Last edited on
One solution is to move C into its own header file, but then C is no longer
declared within A.
If you had them in the same header file you could do this
1
2
3
4
5
6
7
8
9
10
11
class B;
class A {
public:
	struct C {
	};
	B b;
}; 
class B {
public:
	void func(A::C & c) {} ;
};


Personally that's what I would try in this case, but cases like this I would first try to avoid
Hi

I have two classes A and B. A needs to know about B and vice-versa

class A
{
B *pb;
};

class B
{
A *pa;
};

It doesn't compile. Any idea why?
I tried this and didn't work either

class B;

class A
{
B *pb;
};

class B
{
A *pa;
};


1
2
3
4
5
6
7
8
9
10
11
class B;
class A {
public:
	struct C {
	};
	B b;
}; 
class B {
public:
	void func(A::C & c) {} ;
};


em, i don't understand. in the first line, Class B is only a declaration. if i haven't define it, how can i define a member of Class B ? However, a pointer to Class B might be o.k? Why?
i just don't understand
Line 6 doesn't work because sizeof( A ) is directly dependent upon sizeof( B ), which has not yet been defined.
If line 6 were a pointer-to-B instead of an instance, the dependency is broken since sizeof( A ) would then
be dependent upon sizeof( B* ), which is in no way related to sizeof( B ).
1
2
3
4
5
6
7
8
9
10
11
class B;

class A
{
B *pb;
};

class B
{
A *pa;
};


but juan said the code above doesn't work. it surprised me
the size of pointer and reference type is decided by the compiler, am i right ?
Topic archived. No new replies allowed.