//header guard:
#ifndef __CLASS1_H_
#define __CLASS1_H_
#include "class2.h"
class class1
{
class1(Class2* pClass2);
~class1();
public:
void someFunction(); //somefunction that will use an instance of class1.
};
#endif
Obviously implementation files for these classes exist, but when I try and compile I get the following output:
error C2079: 'class2::m_Class1_1' uses undefined class 'class1'
error C2079: 'class2::m_Class1_2' uses undefined class 'class1'
This occurs when class1.cpp is being compiled, I can see why it is happening, the header guard is stopping class1.h from being fully read, I have found a work-around for this which is:
class1.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//header guard:
#ifndef __CLASS1_H_
#define __CLASS1_H_
class class1
{
class1(Class2* pClass2);
~class1();
public:
void someFunction(); //somefunction that will use an instance of class1.
};
#include "class2.h"
#endif
This does work and compile, but I'm not sure if it is standard practice, it just doesn't feel correct to #include at the bottom of a .h file. Any suggestions?
A class must be fully defined before you can use it in any context except as a reference (or pointer). Hence, the compiler complains when you try to define class2 as having a member of type class1 before class1 is fully defined.
In your above example, you can forward declare class2 in class1.h and then not bother
with the include. That will resolve the circular dependency. Of course class1.cpp will
need to include class2.h in order to compile.