I am trying to understand the concept of friendship in nested classes, but I do not understand the concept correctly. I wrote an example program to figure this out, 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 get 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
When I read articles on the Internet, I studied the following points, please comment on them if they are true or not:
- The innerClass function allows you to access all members of the outer class by default.
- To access the private members of innnerClass for an external class, you need to make externalClass as the friend class for innerClass.
Please help by indicating the error in the code, as well as if the points that I understood are correct.
source
share