Home  >  Article  >  Backend Development  >  How to Create Two C Classes that Mutually Reference Each Other?

How to Create Two C Classes that Mutually Reference Each Other?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 08:16:02680browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn