Creating Interdependent Classes in C Through Forward Declarations
In C , how can one establish a relationship between two classes where each contains an object of the other class type?
Direct Object Embedding
Unfortunately, embedding objects of each class directly within the other is not feasible. This circular reference creates infinite space requirements.
Workaround: Pointer-Based Relationship
Instead, we can utilize pointers to establish this relationship. To break the circular dependency, we employ forward declarations.
Forward Declarations
In the class headers (e.g., bar.h and foo.h), we declare the existence of the other class without defining it:
// bar.h class foo; // Declare that the class foo exists class bar { public: foo* getFoo(); protected: foo* f; };
// foo.h class bar; // Declare that the class bar exists class foo { public: bar* getBar(); protected: bar* f; };
Now, each header knows of the other class without their full definition.
Class Implementations
In the corresponding .cpp files, we include the other header to gain access to its full definition:
// foo.cpp #include "bar.h" // ... Implementations of foo methods
// bar.cpp #include "foo.h" // ... Implementations of bar methods
Usage in main()
Finally, in main.cpp, we can create instances of the classes:
#include "foo.h" #include "bar.h" int main() { foo myFoo; bar myBar; }
This strategy allows us to create classes that utilize each other without incurring the circular reference issue.
The above is the detailed content of How to Create Interdependent Classes in C Using Forward Declarations?. For more information, please follow other related articles on the PHP Chinese website!