Page 1 of 1

[SOLVED] Cross referencing classes in C++

Posted: Fri Jun 29, 2007 12:10 am
by AndrewAPrice
If I had the following classes:

classA.h:

Code: Select all

#ifndef CLASSA_H
#define CLASSA_H

#include "classB.h"

class ClassA
{
public:
  // constructor, other public members
private:
      ClassB *child;
      // other private members
};
#endif
classB.h:

Code: Select all

#ifndef CLASSB_H
#define CLASSB

#include "classA.h"

class ClassB
{
public:
  // constructor, other public members
private:
      ClassA *parent;
      // other private members
};
#endif
How could I do this without the compiler (VC++ 8) giving me

Code: Select all

error C2061: syntax error : identifier 'ClassB'
?

Posted: Fri Jun 29, 2007 12:45 am
by AndrewAPrice
I removed the include lines, and just put

Code: Select all

class ClassA;
in classB.h and

Code: Select all

class ClassB;
in classA.h!

Posted: Fri Jun 29, 2007 1:15 pm
by Kevin McGuire
You forgot about the:
#ifndef CLASSB_H
#define CLASSB
_H

Posted: Fri Jun 29, 2007 1:38 pm
by Candy
Kevin McGuire wrote:You forgot about the:
#ifndef CLASSB_H
#define CLASSB
_H
That's a typo. He was stuck with a cyclical reference problem. Solution is to forward declare all you need to know and can forward declare, and to only include the rest. The only case you leave then is the case in which you actually have a recursively-composed structure, which doesn't work by definition since it would be infinitely large.

Posted: Fri Jun 29, 2007 2:14 pm
by Kevin McGuire
I figured he might have missed it, and I did not want to to cost him a half or whole hour of looking when he double includes indirectly the same header and the compiler starts reporting that there are two definitions for something.

Posted: Fri Jun 29, 2007 3:11 pm
by Candy
Kevin McGuire wrote:I figured he might have missed it, and I did not want to to cost him a half or whole hour of looking when he double includes indirectly the same header and the compiler starts reporting that there are two definitions for something.
You're quite right about that.