loop in class definition ?

V

vertigo

Hello
I have:

classA.h file:
#include "classB.h"
classA{
classB *ptr;
};

classA.c file:
#include "classA.h"
.......

classB.h file:
#include "classA.h"
classB{
classA *ptr;
}

classB.c file:
#include "classB.h"
.......

I compile classA.c and classB.c and later link all together.
My problem is that in this case there is redefinition of classA and
classB (because classA.h and classB.h files are included two times).
When i used in *.h files:
#ifndef XXX
#define XXX
......
#endif

*.h files are included once but i do not see their definitions and can
not compile (classB.h do not see definition for classA and classA.h do
not see definition for classB).

How can i solve this problem ?

Thanx
Michal
 
S

Simon Saunders

Hello
I have:

classA.h file:
#include "classB.h"
classA{
classB *ptr;
};

classA.c file:
#include "classA.h"
......

classB.h file:
#include "classA.h"
classB{
classA *ptr;
}

classB.c file:
#include "classB.h"
......

I compile classA.c and classB.c and later link all together.
My problem is that in this case there is redefinition of classA and
classB (because classA.h and classB.h files are included two times).
When i used in *.h files:
#ifndef XXX
#define XXX
.....
#endif

*.h files are included once but i do not see their definitions and can
not compile (classB.h do not see definition for classA and classA.h do
not see definition for classB).

How can i solve this problem ?

Use forward declarations:

classA.h:
class B;
class A
{
class B* ptr;
};

classA.c:
#include "classA.h"
#include "classB.h"
....

(and do the same for classB obviously).

This is covered by the C++ FAQ Lite:

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-38.11
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top