I'm writing a small game engine and I have a little problem. The code below shows the exact situation:

Header1.h

#ifndef _HEADER1
#define _HEADER1

#include "Header2.h"

namespace HNamespace
{
	class HClass1
	{
		public:
			HClass1()
			{
				
			}
			
			~HClass1()
			{
				
			}
			
		HClass2 * A;
		
	};
}

#endif

Header2.h

#ifndef _HEADER2
#define _HEADER2

#include "Header1.h"

namespace HNamespace
{
	class HClass2
	{
		public:
			HClass2()
			{
				
			}
			
			~HClass2()
			{
				
			}
			
		HClass1 * A;
		
	};
}

#endif

Main.cpp

#include "Header1.h"
#include "Header2.h"

int main(int argc, char ** argv){
	
	return 0;
}

Output:
header2.h(21) : error C2143: syntax error : missing ';' before '*'
header2.h(21) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
header2.h(21) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

First error obviously says that HClass1 is not recognised in HClass2. Others are not that important, because they are caused by the first error.

I get that when I use HNamespace::HClass1 instead of just HClass1:
header2.h(21) : error C2039: 'HClass1' : is not a member of 'HNamespace'
(... and the first ones)

Interestingly I don't get any errors on the line where I declare

friend class HClass1;

in HClass2.

I know I can just use "void *" instead of "HClass1 *" and the errors will disappear, but I'd like to see the class names instead of "void".

My questions are: What is happening? What is the solution to that problem?

(I have a feeling the solution is obvious...)

Thanks
Marek

Ok what you need to do is at the beginning of the header file for one of the classes. You need to declare that there "will be a class of this type". You then drop the include for that class from the file.

So take HClass1:

#ifndef _HEADER1
#define _HEADER1


namespace HNamespace
{
        class HClass2;

	class HClass1
	{
		public:
			HClass1()
			{
				
			}
			
			~HClass1()
			{
				
			}
			
		HClass2 * A;
		
	};
}

#endif

You can then leave your HClass2 file as it is.

Edit: You need to make sure your HClass2 file is included somewhere else in the program

Wow, it worked! Thank you :).

Well I didn't think of that way to do it. I will try it with my game engine after I finish my dinner.

This problem is solved.

Thank you again
Marek

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.