c++header-filesinner-classescircular-dependencycode-separation

Separate definition of inner class and enclosing class


What is the proper way to separate the definition of an inner class and an enclosing class into different header files, if the enclosing class has a member variable which is an instance of the inner class?

Here is the header of Outer (the enclosing class):

//outer.h
#ifndef OUTER_H_INCLUDED
#define OUTER_H_INCLUDED

#include "inner.h"

class Outer
{
    class Inner;

public:
    /* public member functions */

private:        
    Inner inner_instance;
};

#endif

And the header of Inner:

//inner.h
#ifndef INNER_H_INCLUDED
#define INNER_H_INCLUDED

#include "outer.h"

class Outer::Inner
{
    /* definition */
};

#endif

This won't compile. The problem is that both classes must see the definitions of each other. Is it possible to break the circular dependency and still keep the definitions separated?


Solution

  • No. The best you can do is store a pointer (or perhaps reference) to the inner class instead, which allows Inner to be incomplete. This is generally known as the pImpl idiom.