Alex Rivera | Logout

Cross referencing included headers in c++ program

Asked 2009-09-15T20:04:11.213
22

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?

Edit
Report

1 Answer

2

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;
};
answered 2009-09-15T20:09:14.720

Your Answer