Home > Backend Development > C++ > body text

How to Create Interdependent Classes in C Using Forward Declarations?

Linda Hamilton
Release: 2024-11-23 20:44:15
Original
896 people have browsed it

How to Create Interdependent Classes in C   Using Forward Declarations?

Creating Interdependent Classes in C Through Forward Declarations

In C , how can one establish a relationship between two classes where each contains an object of the other class type?

Direct Object Embedding

Unfortunately, embedding objects of each class directly within the other is not feasible. This circular reference creates infinite space requirements.

Workaround: Pointer-Based Relationship

Instead, we can utilize pointers to establish this relationship. To break the circular dependency, we employ forward declarations.

Forward Declarations

In the class headers (e.g., bar.h and foo.h), we declare the existence of the other class without defining it:

// bar.h
class foo; // Declare that the class foo exists

class bar {
public:
  foo* getFoo();
protected:
  foo* f;
};
Copy after login
// foo.h
class bar; // Declare that the class bar exists

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

Now, each header knows of the other class without their full definition.

Class Implementations

In the corresponding .cpp files, we include the other header to gain access to its full definition:

// foo.cpp
#include "bar.h"

// ... Implementations of foo methods
Copy after login
// bar.cpp
#include "foo.h"

// ... Implementations of bar methods
Copy after login

Usage in main()

Finally, in main.cpp, we can create instances of the classes:

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

int main() {
  foo myFoo;
  bar myBar;
}
Copy after login

This strategy allows us to create classes that utilize each other without incurring the circular reference issue.

The above is the detailed content of How to Create Interdependent Classes in C Using Forward Declarations?. 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