Question

I have an inclusion pattern as follows:

/*
 * Class1.h
 */

#ifndef CLASS1_H_
#define CLASS1_H_

#include "Class2.h"

namespace Class1_namespace
{

class Class1
{
  Class2* Class2_ptr;
  void Class1_member()
  {
      (*Class2_ptr).Class2_method();
  }
};

}

#endif /* CLASS1_H_ */

/*
 * Class2.h
 */

#ifndef CLASS2_H_
#define CLASS2_H_

#include "Class1.h"

class Class2
{
    Class1_namespace::Class1 Class2_data;

public:
    void Class2_method(){};
};

#endif /* CLASS2_H_ */

/*
 * main.cpp
 */

#include "Class1.h"

int main()
{
    return 0;
}

However, this leads to the error “'Class1_namespace' does not name a type.”

Is this error caused by the ordering of my inclusions?

What are some possible solutions? I'm dubious about forward declarations solving my problem.

Was it helpful?

Solution

Class1 doesn't need to include Class2.

When you have mutual dependency (which you don't -- you could just not include 2 in 1), you can usually solve it by using forward declarations instead of inclusions.

For example, let's say that Class1 looked like this

#include "Class2.h"

namespace Class1_namespace
{

    class Class1
    {
        Class2* class2;
    };

}

Where you think you need the include, you could instead do this:

class Class2;

namespace Class1_namespace
{

    class Class1
    {
        Class2* class2;
    };

}

to break the mutual inclusion.

OTHER TIPS

In class1.h, try removing the unnecessary and circular #include of class2.h. If a circular dependency is required -- or even if not -- consider using forward declarations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top