c++ header files including each other mutually

C++HeaderInclude

C++ Problem Overview


I have two classes both defined in separate header files. Each file has a field that is type of other class. Now I included in header of each file the header of other file, but compiler is generating errors. What am i missing?

C++ Solutions


Solution 1 - C++

You cannot have each class have "a field that is type of other class"; that would be a recursive definition and not only the compiler would not be able to make any sense out of it, it does not even make logical sense.

Each class having a field that is type of the other class is the kind of impossibility that you only see in M.C. Escher drawings, or animations thereof, like this one:

 

                                            based on Escher's

                 B. de Smit and H. W. Lenstra - Source: escherdroste.math.leidenuniv.nl

                     based on Escher's "Print Gallery" Lithograph, 1956, see Wikipedia

 

One of the two fields will have to be a pointer, so as to break the recursive containment, and avoid the logical impossibility.

Which brings us to the next problem: if class B is to contain an instance of class A, then obviously, A has to be declared before class B, so that A is already known to the compiler when compiling B. But if class A is declared before class B, how can we declare a pointer to B in A? Class B is not known yet at the time that A is compiled! The answer to this is a special construct known as forward declaration which exists precisely in order to accommodate situations like this. A forward declaration of class B looks like this:

class B;

All it is telling the compiler is that there will be a class called B. It does not tell the compiler anything about the contents of class B, so there is very little we can do with it, but we can do one thing: declare pointers to B.

So, the full solution to the problem looks like this:

file "A.h":

/* This is called a "forward declaration".  We use it to tell the compiler that
   the identifier "B" will from now on stand for a class, and this class will be
   defined later.  We will not be able to make any use of "B" before it has been
   defined, but we will at least be able to declare pointers to it. */
class B;

class A
{
    /* We cannot have a field of type "B" here, because it has not yet been
       defined. However, with the forward declaration we have told the compiler
       that "B" is a class, so we can at least have a field which is a pointer 
       to "B". */
    B* pb; 
}

file "B.h":

#include "A.h"

class B
{
   /* the compiler now knows the size of "A", so we can have a field
      of type "A". */
   A a;
}

Solution 2 - C++

You shouldn't include the header files inside the other ones, just include the header files in your source files.

In the headers you can use a forward declaration:

// In Class1.h
class Class2;

// In class2.h
class Class1;

Also you can protect against a file being included twice using the preprocessor:

// Class1.h
#ifndef __CLASS_1_H
#define __CLASS_1_H

// content

#endif

Solution 3 - C++

I know this is an old topic but maybe you are still interested in solution!

Actually in C++ you can use two classes recursively without using pointers and here is how to do it.

file: a.h

#include <b.h>

class A {
    B<> b;
}

file: b.h

class A;

template<typename T = A>
class B {
    T a;
}

file: main.cpp

#include "a.h"    
A a;

and that's all!

of course this is just for curiosity :)

Solution 4 - C++

You probably want to use forward declaration, unless you actually want to put instance of each class in each other. In which case you shouldn't use anything.

Solution 5 - C++

If B can only exist within A, I seem to be able to create A and B without using a pointer. B has to simply forward declare A and not include it (avoiding the recursive inclusion).

In my case, a Document has a Section which gets a reference to its Document.

section.h

class Document;

class Section
{
    public:
        Section(Document& document) : document{document} {} 
    private:
        Document& document;
};

document.h

#include "section.h"

class Document
{
    public:
        Document() : section{*this} {}
    private:
        Section section;
};

main.cpp

#include "document.h"

int main()
{
    Document document{};
}

This code compiles with g++ and runs on Linux.

A (complex) set of ifdef might enable it for other cases, but I'm not sure about the readability...

Solution 6 - C++

Besides the possibility of forward declaration - if it seems that you need two classes mutually within the other it is out of my experience a sign for a mistake in the depth of inheritance. Eather the classes are a kind of siblings and you should create a parent class for both. Or you are trying to use a class that is in fact a parent class within one that should have a sibling from this parent class. Then you should create this sibling as a third class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMegaManXView Question on Stackoverflow
Solution 1 - C++Mike NakisView Answer on Stackoverflow
Solution 2 - C++Matt LaceyView Answer on Stackoverflow
Solution 3 - C++BoynuxView Answer on Stackoverflow
Solution 4 - C++Michael Krelin - hackerView Answer on Stackoverflow
Solution 5 - C++a.l.eView Answer on Stackoverflow
Solution 6 - C++Thomas_MView Answer on Stackoverflow