Home > Article > Backend Development > How to Create Two C Classes that Mutually Reference Each Other?
Two Classes Mutually Referencing Each Other
Creating two C classes that each contain an object of the other type directly is not possible due to the circular reference issue. However, a workaround involves employing pointers to refer to each other.
Forward Declarations and Pointer Usage
To achieve this, use forward declarations in the header files to establish the existence of the other class without defining it:
// bar.h class foo; // Say foo exists without defining it. class bar { public: foo* getFoo(); protected: foo* f; };
// foo.h class bar; // Say bar exists without defining it. class foo { public: bar* getBar(); protected: bar* f; };
Then, in the respective .cpp files, include the other header to define the class fully:
// bar.cpp #include "foo.h" foo* bar::getFoo() { return f; }
// foo.cpp #include "bar.h" bar* foo::getBar() { return f; }
This approach breaks the circular reference loop as the forward declarations allow the classes to acknowledge each other's existence without including their headers, preventing infinite space issues for the objects.
The above is the detailed content of How to Create Two C Classes that Mutually Reference Each Other?. For more information, please follow other related articles on the PHP Chinese website!