C++ interdependant classes
I have two C++ classes that depend on each other. Here's a simple example:
Code:
class A Code:
$ g++ test.cpp |
Sure:
Code:
class B; |
I guess there could be cases simple enough that works (just predeclaring B).
Quote:
Code:
class 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. |
Hi, Mtk358 -
Glad you're squared away. Let me elaborate a bit on what johnsfine was trying to say: 1. You should always strive to separate your interface from your implementation (one of the few things I dislike about Java and C# is they tend to make it harder to do this). 2. If you did this, your interface would go in a .h header, your implementation in one or more .cpp modules ... and the syntax I gave you should work perfectly. 3. Otherwise, you might have problems trying to access any members of the class you forward referenced. Here's an alternate example: Code:
// myheader.h Code:
// mymodule.cpp |
I do separate the interface and implementation. I didn't in the example becasue it's simpler and still causes the same error.
|
http://stackoverflow.com/questions/3...ursive-classes - pay attention to pointers to classes.
|
MTK358 -
Quote:
Again - glad you're squared away :) Sincerely .. PSM |
All times are GMT -5. The time now is 02:44 AM. |