tags:

views:

327

answers:

4

Hello,

I am curious about a scenario set up like the following example:

Here is code that would be placed in a file called Header1.h:

#ifndef HEADER1_H
#define HEADER1_H

#include "Header2.h"

class Class1
{
 Class2 class2Instance;
};

#endif

Here is code that would be placed in a file called Header2.h:

#ifndef HEADER2_H
#define HEADER2_H

#include "Header1.h"

class Class2
{
 Class1 class1Instance;
};

#endif

I get error messages when I do this (because of the includes I assume), but it feels like I would need to do this in order to include each of the objects in the separate classes. Can anyone help me accomplish this, what am I doing wrong?

+5  A: 

The problem is that the size of Class1 depends on Class2, and vice-versa. Therefore, there's no way to calculate the size for either one. Forward-declare one of the classes, and change one of the attributes to be a pointer or reference:

#ifndef HEADER2_H
#define HEADER2_H

class Class1;
class Class2
{
 Class1 *class1Instance;
 // or
 Class1 &class1Instance;
};

#endif
John Millikin
This is a great answer but it only solves half of my problem. I am still placing these two classes in two separate headers. I get an error for just the include statements as I type them, without the circular class inclusion. Do you know how to circumvent this problem without placing them in the same header.
Patrick Hogan
What error are you receiving? The code you posted doesn't have any issues with the include directives.
John Millikin
Then perhaps you should give us a revised example reflecting your current code and also tell us exactly what errors you're getting.
TheUndeadFish
+1  A: 

What you have is a classic circular reference. It's already been discussed here on Stack Overflow. Just apply the accepted answer on that thread, while substituting "struct" for "class", and you're golden.

Edited for clarity

Randolpho
I believe the accepted answer does exactly that. So change the word "struct" in the accepted answer to the word "class" and the pattern is the same. Please take back your unwarranted downvote, kthxbai
Randolpho
There. 'Tis done.
Randolpho
+2  A: 

You can't have Class2 contain an instance of Class1 AND have Class1 contain an instance of Class2. What you can do is have each class contain a reference or pointer to and instance of the other class type (with appropriate forward references). i.e.


class Class2;
class Class1
{
    Class2& class2Instance;
};


class Class1;

class Class2
{
    Class1& class1Instance;
};
Ferruccio
+3  A: 

The two structures infinitely recurse on one another -- to know Class1's size you need to know the size of Class2 which requires the size of Class1, etc. The workaround for this is to use a pointer in at least one of the cases:

#ifndef HEADER1_H
#define HEADER1_H

class Class2; // no need to include Header2

class Class1
{
    Class2* class2Instance;
}

#endif
fbrereto