I have two classes, let's call them class A and class B with mutual
dependencies as shown below and where implementation is inside .h (no cpp)
#include "classB.h"
class A
{
};
#include "classA.h"
class B
{
};
So to solve this I am using forward declaration in class B and I had
to mo ve implementation in a .cpp
class A;
class B
{
...
};
IS there another way to solve this and to keep implementation only in .h ?
Remove the circular dependency?
Seriously, though, that *is* the kosher way of resolving circular
dependencies. There's no better way (besides redesigning your program to
remove the circular dependency in the first place, of course).
In fact, it's a good custom to always prefer forward declarations in
header files whenever possible, rather than #including more header files
(even if there wasn't any mandatory technical reason to do that).
Reducing include dependencies has many benefits.
Everything you've written should work just fine, modulo the "..." in
the second definition of class B.. The problem must be in the code that
you didn't include.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
> On 2008-10-30 15:27:55 -0400, Mosfet <mos...@anonymous.org> said:
>
>> Hi,
>>
>> I have two classes, let's call them class A and class B with mutual
>> dependencies as shown below and where implementation is inside .h (no
>> cpp)
>>
>>
>> #include "classB.h"
>> class A
>> {
>>
>> };
>>
>> #include "classA.h"
>> class B
>> {
>> };
Whoops, the preceding won't, of course, work. I must be having a bad day.
You've not shown enough info.
Solving mutual dependencies depends on whether you have a circular
dependancy, which may not be finite.
what if A has_a B which in turn has_an A which has_a B ... infintely?
Why do you want to have the implementation in .h. This requires at least
that all of your functions are declared inline (implicitely or
explicitely). If the compiler cares about that is another question, but
at least it blows up the compile time of your project significantly.
If you have a cyclic dependancy of the /declaration/ of your classes
e.g. because of the use of certain smart pointers like intrusive_ptr,
then you have a serious problem. If only the implementaions depend on
each other you have no problem.
Marcel
Actually if you have a circular reference with reference-counting
smart pointers, you do have a problem already.