Circular includes and forward declarations

I'm having problems with circular dependencies here's a little example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class A
{
    int doSomething(B bIn)
    {
         return bIn.getNum();
    }
};

class B
{
    int getNum()
    {
	return 2;
    }

     void foo(A aIN)
     {
	cout << "FOO";
     }
};


I saw a post about this that had been archived but I couldn't seem to get that solution to work.

Here's that post: http://www.cplusplus.com/forum/general/8023/

I tried to use an include on just one of the files but it would go into the class e.g. class a and the fail to compile because class b had not been declared. I also put the include in both files that seemed to put the compiler in an infinite loop. Any ideas?
Last edited on
Perhaps you could use a template? Its an easy, but inelegant solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

class A
{
    template<class T>
    int doSomething(T bIn)
    {
         return bIn.getNum();
    }
};

class B
{
    int getNum()
    {
	return 2;
    }

     void foo(A aIN)
     {
	cout << "FOO";
     }
};


Very simple.
I think that this feature of templates - lets call it 'late binding' - should be incorporated into
the standard C++ compilation process (or would that just make more work for hard pressed C++
compiler writers).
Or you could do this the right way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// a.h - give it a header guard
class B;

class A
{
    int doSomething(B bIn);
};

#include "b.h"

inline int A::doSomething(B bIn)  // or instead of making it inline, put it in a cpp
{
     return bIn.getNum();
}



See this:
http://www.cplusplus.com/forum/articles/10627/#msg49679

Sections 4, 6, 7
Topic archived. No new replies allowed.