class B is nested insider class A but it does not declare the class B as its friend. However, the member function void B::print(A a) can access to the private member data int a, b of class A. The books introduce the nested class must be declared as friend then to access the private member data. Does this have been changed in c++ standard?
code:

#include <iostream>

using namespace std;
class A
{
	int a , b;
public:
	
	A():a(1),b(2){}
	//class B;
	//friend class B;
	class B
	{
	public:
		void print(A aa)
		{
			cout << "A.a = " << aa.a << ", A.b = " << aa.b <<endl; //aa.a and aa.b are private member data of class A
		}
	};
};

int main()
{
	A a;
	A::B b;
	b.print(a);
}

Recommended Answers

All 4 Replies

Because its inside the class definition. Technically, you can access a
class data member , if you are trying to access it inside its definition.

Think of class B like a member function accessing its private data,
except its a class instead of a function.

But the book "Thinking in c++" By Bruce Eckel says the nested class must declare as:

class A
{
public:
 class B;
friend class B;
class B{};
};

I am not sure whether the standard changed.
please see nested friend in Eckel's book.

Nested class means that a class is "nested" i.e, in scope of
the outer class.
Thus the code :

class Outer
{
public:
    class  Inner{ ... };
}

has a nested class called Inner because its inside the scope of the
outer class. And if public, it could be used with the scope resolution operator ::, like so Outer::Inner::someFunc

Thank you firstPerson,

It is C++ standard 11.8.

11.8 Nested classes http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf
A nested class is a member and as such has the same access rights as any other member. The members of an enclosing
class have no special access to members of a nested class; the usual access rules (clause 11) shall be obeyed. [ Example:

class E 
{
	int x;
	class B { };

	class I 
	{
		B b; / / OK: E::I can access E::B
			int y;
		void f(E* p , int i)
		{
			p->x = i; / / OK: E::I can access E::x
		}
	};
	int g(I* p)
	{
		return p->y; / / error: I::y is private
	}
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.