To create an Outer object, the layout of the class memory must be known, in which case it is not (precisely because of Inner incompleteness).
The way to do this is to use a pointer, then the declaration will work forward (since the pointer has a fixed size, and then the Outer memory layout will be allocated).
What I mean:
And then, in the source file for the Outer class, define
// include header file for Outer and Inner classes // source file Outer::Outer() { i = new Inner( *this ); }; Outer::~Outer() { delete i; };
You need to do this in the source file because you need to include header file of the Inner class (you cannot include it directly in the header file because you will encounter a circular dependency (the two header files will include each other) since the header file Inner must also have an Outer header file).
This is also known as pImpl idiom - an "implementation pointer", and often Inner is called Impl and a member of pImpl or something like that, depending on the encoding convention used. The idea is to hide any implementation details, such as private / protected members (functions, data).
Kiril Kirov
source share