Mayank Jain Mayank Jain - 1 month ago 7
C++ Question

Friendship in nested classes C++

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.

Answer

If you want to define innerClass outside of outerClass, here is how to do it:

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

class outerClass::innerClass // definition
{
};

The rest is OK, except of obj.b=5. The class outerClass is allowed to access innerClass::b, the function main() is not.

Demo


innerClass can access all the members of outerClass by default.

Right. From the standard [class.access.nest]:

A nested class is a member and as such has the same access rights as any other member.


For outerClass to access private members of innnerClass we need to make outerClass as friend class to innerClass.

Right. From the standard [class.access.nest]:

The members of an enclosing class have no special access to members of a nested class;

Comments