Friendship in nested C ++ classes

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.

+4
source share
3 answers

innerClass outerClass, :

class outerClass
{
    class innerClass; // forward declaration
};

class outerClass::innerClass // definition
{
};

, obj.b=5. outerClass innerClass::b, main() - .


externalClass .

. [class.access.nest]:

, , .


externalClass innnerClass, externalClass innerClass.

. [class.access.nest]:

;

+3

class innerClass; outerClass - class, .

, outerClass::innerClass .

innerClass,

class innerClass
{

class .

friend class outerClass; innerClass.

+4

, nested class friend class
friend class nested class
nested class friend class

:

class A {};
class B {};

A B, B A. A, B.
, Forward Declaration
:

class B;       // forward declaration
class A {};    // A knows the B
class B {};    // B knows the A
0
source

Source: https://habr.com/ru/post/1657508/


All Articles