Home > Backend Development > C++ > body text

How to Create Interdependent C Classes Without Circular References?

Linda Hamilton
Release: 2024-11-09 22:20:04
Original
939 people have browsed it

How to Create Interdependent C   Classes Without Circular References?

Creating Interdependent Classes in C

This question explores how to create two C classes that each contain an object of the other class type. However, this direct approach leads to an error due to circular references.

Direct Implementation

Consider the following header files, which attempt to define two classes, foo and bar, each with a protected member of the other class type:

// bar.h
#include "foo.h"
class bar {
  foo f;
};

// foo.h
#include "bar.h"
class foo {
  bar b;
};
Copy after login

Compiling this code results in an error, as both headers include each other and create a circular reference.

Workaround: Forward Declarations and Pointers

To break this reference cycle, we can use forward declarations and pointers. Forward declarations allow us to declare the existence of a class without defining its members.

The modified header files are:

// bar.h

class foo; // Forward declaration of foo

class bar {
  foo* f;
};

// foo.h

class bar; // Forward declaration of bar

class foo {
  bar* b;
};
Copy after login

With these forward declarations, the headers can include each other without creating a circular reference. The actual definition of the class members is then placed in the corresponding .cpp files, where the necessary headers are included.

Using Pointers

To use the classes with pointers, we create instances of foo and bar with pointers to each other:

// main.cpp

#include "foo.h"
#include "bar.h"

int main() {
  foo myFoo;
  bar myBar;
  myFoo.f = &myBar; // Assign the address of myBar to myFoo's f
  myBar.b = &myFoo; // Assign the address of myFoo to myBar's b
}
Copy after login

This workaround allows us to create classes with interdependent objects using pointers, breaking the reference cycle and creating a valid program.

The above is the detailed content of How to Create Interdependent C Classes Without Circular References?. 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