How to create two classes in C++ which use each other as data?

You cannot have two classes directly contain objects of the other type, since otherwise you’d need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.)

You can indeed do this by having the two classes store pointers to one another, though. To do this, you’ll need to use forward declarations so that the two classes know of each other’s existence:

#ifndef BAR_H
#define BAR_H

class foo; // Say foo exists without defining it.

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

and

#ifndef FOO_H
#define FOO_H

class bar; // Say bar exists without defining it.

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

Notice that the two headers don’t include each other. Instead, they just know of the existence of the other class via the forward declarations. Then, in the .cpp files for these two classes, you can #include the other header to get the full information about the class. These forward declarations allow you to break the reference cycle of “foo needs bar needs foo needs bar.”

Leave a Comment