[SOLVED] Cross referencing classes in C++

Programming, for all ages and all languages.
Post Reply
User avatar
AndrewAPrice
Member
Member
Posts: 2303
Joined: Mon Jun 05, 2006 11:00 pm
Location: USA (and Australia)

[SOLVED] Cross referencing classes in C++

Post 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'
?
My OS is Perception.
User avatar
AndrewAPrice
Member
Member
Posts: 2303
Joined: Mon Jun 05, 2006 11:00 pm
Location: USA (and Australia)

Post 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!
My OS is Perception.
User avatar
Kevin McGuire
Member
Member
Posts: 843
Joined: Tue Nov 09, 2004 12:00 am
Location: United States
Contact:

Post by Kevin McGuire »

You forgot about the:
#ifndef CLASSB_H
#define CLASSB
_H
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Post 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.
User avatar
Kevin McGuire
Member
Member
Posts: 843
Joined: Tue Nov 09, 2004 12:00 am
Location: United States
Contact:

Post 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.
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Post 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.
Post Reply