I guess there could be cases simple enough that works (just predeclaring B).
Quote:
Originally Posted by paulsm4
Code:
class B;
class A
{
public:
B foo() {}
};
class B
{
public:
A bar() {}
};
int main()
{
return 0;
}
|
But in most real world examples, you need to go a step further:
Code:
class B;
class A
{
public:
B foo();
};
class B
{
public:
A bar() {}
};
B A::foo() {}
int main()
{
return 0;
}
In addition to predeclaring B before defining A, I also only declared (not defined) foo inside the definition of A. Then I defined A::foo after defining B.
(In all these examples, I am assuming the {} stands for actual code rather than literally {})
You (MTK358) need to understand the relationship between declaring and defining:
The code in the first post declares and defines A together as one step, similarly for foo, B and bar. But each of those could have declare split from define if you choose.
You cannot avoid declaring A::foo() within defining A, and you cannot avoid declaring B::bar() within defining B.
The way the code looks, it is very clear:
1) Declaring B must precede declaring foo.
2) Declaring A must precede declaring bar.
It seems pretty clear (despite paulsm4's example):
3) Defining B must precede defining foo.
4) Defining A must precede defining bar.
My example sorts all that out by the following sequence:
Declaring B
Defining A including declaring foo
Defining B including declaring and defining bar
Defining foo.
It may be better style (though not needed in this example) to also split defining bar from declaring bar.