I am trying to understand concept of friendship in nested classes but I am not getting the concept properly. I have written a sample program to understand it but the program is not working
#include<iostream>
using namespace std;
class outerClass
{
private:
int a;
public:
class innerClass;
bool print(innerClass);
};
class innerClass
{
friend class outerClass;
private:
int b;
public:
innerClass() =default;
};
bool outerClass::print(outerClass::innerClass obj)
{
cout<<"Value of b in inner class is:"<<obj.b;
}
int main()
{
outerClass in;
outerClass::innerClass obj;
obj.b=5;
in.print(obj);
}
I am getting below errors:
try.cpp: In member function ‘bool outerClass::print(outerClass::innerClass)’:
try.cpp:26:6: error: ‘obj’ has incomplete type
try.cpp:11:15: error: forward declaration of ‘class outerClass::innerClass’
try.cpp: In function ‘int main()’:
try.cpp:34:28: error: aggregate ‘outerClass::innerClass obj’ has incomplete type and cannot be defined
As I read through articles on internet I learnt following points please comment on them if they are correct or not:
- innerClass can access all the members of outerClass by default.
- For outerClass to access private members of innnerClass we need to make outerClass as friend class to innerClass.
Please help in pointing out the mistake in code and also if the points I understood are correct.