header reference problem

Hi,

I've just started developping my program today and i recieve some errors already.
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//A.hpp
#ifndef A_HPP
#define A_HPP

#include "b.hpp"

class A {  

public:
	A(  );

private:
	B* _b;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//B.hpp
#ifndef B_HPP
#define B_HPP

#include "a.hpp"

class B{  

public:
	B( A* );

private:
	A* _a;
};


1
2
3
4
5
6
//a.cpp
#include "a.hpp"

A::A( ){
	_b = new B;
};


1
2
3
4
5
6
//b.cpp
#include "b.hpp"

B::B(A* a){
	_a = a;
}


1
2
3
4
5
6
7
//main.cpp
#include "a.hpp"

int main( ) {
	A();
	return 0;
}


These are the errors i recieve ( linux gcc compiler ):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
In file included from a.hpp:4,
                 from main.cpp:1:
b.hpp:8: error: expected ‘)’ before ‘*’ token
b.hpp:10: error: ISO C++ forbids declaration of ‘A’ with no type
b.hpp:10: error: expected ‘;’ before ‘*’ token
In file included from a.hpp:4:
b.hpp:8: error: expected ‘)’ before ‘*’ token
b.hpp:10: error: ISO C++ forbids declaration of ‘A’ with no type
b.hpp:10: error: expected ‘;’ before ‘*’ token
In file included from a.hpp:4,
                 from a.cpp:1:
b.hpp:8: error: expected ‘)’ before ‘*’ token
b.hpp:10: error: ISO C++ forbids declaration of ‘A’ with no type
b.hpp:10: error: expected ‘;’ before ‘*’ token
In file included from b.hpp:4:
a.hpp:11: error: ISO C++ forbids declaration of ‘B’ with no type
a.hpp:11: error: expected ‘;’ before ‘*’ token
In file included from b.hpp:4,
                 from b.cpp:1:
a.hpp:11: error: ISO C++ forbids declaration of ‘B’ with no type
a.hpp:11: error: expected ‘;’ before ‘*’ token

a.hpp cannot include b.hpp if b.hpp includes a.hpp. It's a circular dependency problem.

The correct way to do this is to forward declare.

Read section 4 of this article: http://www.cplusplus.com/forum/articles/10627/#msg49679
You'll need to forward declare A and B in your header files:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//A.hpp
#ifndef A_HPP
#define A_HPP

class B;

class A {  

public:
	A(  );

private:
	B* _b;
};
ok, thanks for advice, the article was really helpful!

hannesvdc
Topic archived. No new replies allowed.