Home >Backend Development >C++ >How can you create interdependent classes in C without infinite recursion?

How can you create interdependent classes in C without infinite recursion?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 08:38:02691browse

How can you create interdependent classes in C   without infinite recursion?

Interdependent Classes in C : Utilizing Forward Declarations

Attempting to create two classes that contain objects of each other's type directly leads to a problem of infinite recursion. To achieve this, a workaround using pointers and forward declarations is necessary.

In the scenario provided, the circular dependency between the foo and bar classes is causing an error. To resolve this, forward declarations are employed to announce the existence of each class without defining it:

// bar.h
#ifndef BAR_H
#define BAR_H

// Declares the existence of foo without defining it
class foo;

class bar {
public:
  foo* getFoo();
protected:
  foo* f;
};
#endif
// foo.h
#ifndef FOO_H
#define FOO_H

// Declares the existence of bar without defining it
class bar;

class foo {
public:
  bar* getBar();
protected:
  bar* f;
};
#endif

These forward declarations allow the foo and bar headers to be independent, avoiding the circular reference. The full definitions of each class, including the pointer members, are then provided in their respective .cpp files.

Usage Example:

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

int main(int argc, char **argv) {
  foo myFoo;
  bar myBar;
}

Now, the program compiles successfully because the forward declarations enable the classes to know about each other indirectly. They can now store pointers to one another, breaking the cycle and allowing for the creation of interdependent classes.

The above is the detailed content of How can you create interdependent classes in C without infinite recursion?. 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