Originally Posted by
Daved
If you are only declaring a pointer to Class2 in Class1, you don't need to #include "Header2.hpp" in Header1.hpp. Just use a forward declaration instead:
The same is true for the declaration of Class1 in Class2.
However, since you
use the pointers in the inline functions f1() and f2(), it does require the actual header to be included. To solve the issue, you must define either f1() or f2() in a source file and not inside the class definition. Whichever one you choose to move (or both) means that you can use the forward declaration in that header file, removing the circular include.
Thanks that's very helpful.
Now suppose I have a typedef instead. Is there any such thing as a "forward typedef declaration"?
e.g.
Code:
//Main.cpp
#include <stdio.h>
#include "Header1.hpp"
int main()
{
Class1 c1;
return 0;
}
Code:
//Header1.hpp
#ifndef HEADER1_HPP
#define HEADER1_HPP
#include "Header2.hpp"
class Class1;
typedef ClassArray *Class1;
class Class1 {
private:
Class2 *c;
public:
int i;
int f1() { return c->i; }
};
#endif
Code:
//Header2.hpp
#ifndef HEADER2_HPP
#define HEADER2_HPP
#include "Header1.hpp"
class Class2 {
private:
ClassArray *c;
public:
int i;
int f2() {return c->i;}
};
#endif
Ignore the functions, even comment them out if you like. They're not my main concern.
Is there anyway to forward-declare the typedef in Header2, like you did with the class?
Thanks.