Reputation: 5064
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?
Upvotes: 22
Views: 25441
Reputation: 472
file:header1.h
#ifndef HEADER1_H
#define HEADER1_H
class Class2; // no need to include Header2
class Class1
{
Class2* class2Instance;
}
#endif
file:header1.cpp
#include "header2.h" // do include Header2 here, otherwise you will get errors
adapted from here
Upvotes: 9
Reputation: 56391
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
Upvotes: 1
Reputation: 35925
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
Upvotes: 3
Reputation: 100648
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;
};
Upvotes: 2
Reputation: 200766
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
Upvotes: 37