Multiple source files to declare inner classes and friendship

c++

Solution

This will work as long as the definition of `A` does not rely on `B` being a complete type. (So `A` can contain a reference or pointer to `B`, but not an actual `B` instance because the compiler doesn't know how much space to allocate for `B` until it has seen `B`'s definition.)

In source2.h, you would define the class you declared in source1.h by specifying the scope:

class A::B {
    // ...
};

In source4.cpp, you would also need to specify scope. For example, if `B`'s definition declares a no-arg constructor that does nothing:

A::B::B() { }

It works exactly the same as defining any other class or class members, you just have to prepend `A::` to `B` to let the compiler know where the class is.

I have written a complete and working example of this technique.

Regarding "friendship" which I assume means access to class/object members, nested classes have no special access in either direction.1 The inner class does not have access to any members of the outer class except those it would normally have access to, and the same rule applies in the other direction. If you want the inner class to have full access to the members declared in the outer class, it will be necessary to add an explicit friend declaration to the outer class.

1 This is true in C++03 according to the standard (ANSI/ISO C++ 11.8.1: "The members of a nested class have no special access to members of an enclosing class...") but in C++11 the child class is implicitly a friend of the parent class. Some compilers act as though there is an implicit friendship declared in the parent class even in C++03, but this behavior cannot be considered portable. To be safe, explicitly declare the friendship. This will work equally well on both C++03 and C++11.

Problem

Apologies for my ignorence. I couldn't figure out how to declare body of an inner class using different source files. What i want to achieve is something like this: source1.h: ``` class A { class B; } ``` source2.h: ``` class B { // } ``` source3.cpp: `//Implementation of A` source4.cpp: `//Implementation of B` Extra: How friendship between A and B is implied in these kind of declarations?

Original source