I have 4 classes, A, A1, B, and B1. class A contains a private nested class A1, and class B contains a private nested class B1. I want the constructor for class B::B1 to have access to the private data members of objects of type A::A1. My solution for this was to use the keyword 'friend'. I'm having trouble getting mutual friendship between the outer classes to work, however, and online guides don't account for friendship between two private, nested classes.
The plan is to make B a friend of A so B1 knows about A1. Then make A a friend of B so A1 knows about B1. Then make B1 a friend of A1 so B1 can access the private data members of A1. Here is some code that fails to do that. You can feel free to ignore it.
//A.h
#pragma once
#include "B.h"
class A {
friend class B;
private:
class A1 {
friend class B::B1;
private:
int num = 3;
};
A::A1 a1;
}
//B.h
#pragma once
class A;
class B {
friend class A;
//stuff
private:
class B1;
public:
B1& b; // I would prefer this to not be a reference
B(A a); // Error: incomplete type
};
// B.cpp
#include "B.h"
#include "A.h"
class B::B1{
B::B1(A::A1 a1) {
int num = a.num;
};
int num;
};
B::B(A a) : b(a.a1) {}
There appear to be many errors with this code, but there were many different kinds of errors in all of my attempts to get this to work. An explanation of these errors would be helpful, but I'm seeking a working example of how to get the friendships and forward-declarations right.