Creating Classes That Share Instances of Each Other in C
When attempting to create two classes in C , where each class requires an object of the other class as a member, a compilation error may occur. This is because direct object inclusion leads to an infinite loop in memory allocation.
Solution: Use Pointers as Class Members
To circumvent this issue, create pointers as class members instead of direct objects. This approach involves forward declarations to announce the existence of classes without providing their full definitions.
In bar.h:
#ifndef BAR_H #define BAR_H class foo; // Forward declare foo class bar { public: foo* getFoo(); protected: foo* f; }; #endif
In foo.h:
#ifndef FOO_H #define FOO_H class bar; // Forward declare bar class foo { public: bar* getBar(); protected: bar* f; }; #endif
In their respective .cpp files, include the headers for the other classes:
// foo.cpp #include "foo.h" #include "bar.h" // bar.cpp #include "bar.h" #include "foo.h"
This approach breaks the circular reference loop and allows for the creation of classes that utilize instances of each other through pointers.
The above is the detailed content of How to Create Classes That Share Instances of Each Other in C ?. For more information, please follow other related articles on the PHP Chinese website!