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

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

Patricia Arquette
Release: 2024-11-10 08:16:02
Original
715 people have browsed it

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;
};
Copy after login
// foo.h
class bar; // Say bar exists without defining it.

class foo {
public:
  bar* getBar();
protected:
  bar* f;
};
Copy after login

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; }
Copy after login
// foo.cpp
#include "bar.h"

bar* foo::getBar() { return f; }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template