Home > Backend Development > C++ > body text

How to Create Classes That Share Instances of Each Other in C ?

Linda Hamilton
Release: 2024-11-11 08:22:02
Original
653 people have browsed it

How to Create Classes That Share Instances of Each Other in C  ?

Creating Classes That Share Instances of Each Other in C

When attempting to create two classes in C , where each class requires an object of the other class as a member, a compilation error may occur. This is because direct object inclusion leads to an infinite loop in memory allocation.

Solution: Use Pointers as Class Members

To circumvent this issue, create pointers as class members instead of direct objects. This approach involves forward declarations to announce the existence of classes without providing their full definitions.

In bar.h:

#ifndef BAR_H
#define BAR_H

class foo; // Forward declare foo

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

In foo.h:

#ifndef FOO_H
#define FOO_H

class bar; // Forward declare bar

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

In their respective .cpp files, include the headers for the other classes:

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

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

This approach breaks the circular reference loop and allows for the creation of classes that utilize instances of each other through pointers.

The above is the detailed content of How to Create Classes That Share Instances of Each Other in C ?. 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