-
Recursive Includes
Hello, I'm trying to implement a sort of callback object, but having some trouble with a recursive include problem, to demonstrate:
Code:
#ifndef TEST1_HPP_
#define TEST1_HPP_
#include "test2.hpp"
class A {
B *b;
public:
A(B *obj) {
b = obj;
}
void func() {
b->print();
}
};
#endif /*TEST1_HPP_*/
Code:
#ifndef TEST2_HPP_
#define TEST2_HPP_
#include "test1.hpp"
class B {
private:
A a;
public:
B() : a(this) {}
void test() {
a.func();
}
void print() {
std::cout << "Hello World!" << std::endl;
}
};
#endif /*TEST2_HPP_*/
Code:
#include "test1.hpp"
int main() {
return 0;
}
EDIT: The errors in question are:
Code:
In file included from test2.hpp:4,
from test.cpp:3:
test1.hpp:7: error: ISO C++ forbids declaration of ‘B’ with no type
test1.hpp:7: error: expected ‘;’ before ‘*’ token
test1.hpp:10: error: expected `)' before ‘*’ token
test1.hpp: In member function ‘void A::func()’:
test1.hpp:15: error: ‘b’ was not declared in this scope
In file included from test.cpp:3:
test2.hpp: In constructor ‘B::B()’:
test2.hpp:11: error: no matching function for call to ‘A::A(B* const)’
test1.hpp:6: note: candidates are: A::A()
test1.hpp:6: note: A::A(const A&)
The obvious question is, what am I doing wrong in trying to get this to work?
-
Don't know what IDE you're using, but you should be able to get the output of just the pre-processor (before compilation even starts). You'll see that one of your classes is defined before the other, so calling B in the class A definition won't work, since B hasn't happened yet.
I think you'll need a forward declaration (like "class B;") so that the name B is recognized as a type.
-
The definition of class A doesn't need the definition of class B. Therefore, don't include test2.hpp, but instead just declare the class:
Code:
class B;
class A { ... };
However, the definitions of A's members do need the definition of B, so separate them out into the implementing source file.
Code:
#include "test1.hpp"
#include "test2.hpp"
void A::func()
{
b->print();
}
-