Interdependent classes

[Hi, let me describe briefly a problem.
I have the following two classes A and B, defined in two header files Afile.h and Bfile.h respectively:]

[/
class A
{
....
....
friend B::B(A a);
};

class B
{
public:
B(A a) { .... }
....
....
};
]

[The constructor of B is a friend of A so that it can access the private members of A.
If I include these files in main.cpp file by means of the directives]

[/
#include "Afile.h"
#include "Bfile.h"
]

[it clearly does not compile because class A needs the definition of class B.
Similarly, if I put in main.cpp:]

[/
#include "Bfile.h"
#include "Afile.h"
]

[it does not compile because B class needs the definition of A class.

Then, I put the declaration of B in Afile.h:]

[/
class B;
class A
{
....
....
friend B:B(A a);
};
]

[and the following directives in main.cpp file:]

[/
#include "Afile.h"
#include "Bfile.h"
]

[but it still does not compile and I get
error C2027: use of undefined type 'B'.

What's wrong and how can I fix the problem?]

closed account (48T7M4Gy)
http://stackoverflow.com/questions/4757565/c-forward-declaration

Might help?
@kemort - A good suggestion, but a forward declaration is not going to help as written, since the compiler needs the full declaration of each type to process each class declaration. The OP tried that.
1
2
3
class B;  // forward
class A
{ ...


@OP - The only way around this is to use a construct that does not require the full declaration of each class to compile the other class declaration. This typically means declaring one class forward then using a pointer to that class since a pointer does not need a fully specified type at declaration time.
Last edited on
I'm studying the problem carefully based on your suggestions.
Thank you to both of you.
closed account (48T7M4Gy)
@AbstractNonsense
And that's exactly what the article says. Well done. Well (mis)read. Thanks for your approval, where would I be without it?
Topic archived. No new replies allowed.