Link to home
Create AccountLog in
Avatar of williamcampbell
williamcampbellFlag for United States of America

asked on

Nested Class - Friend Class - Private Variable

Quick Question about Nested Classes and Freind Scope

In the code below ...

Visual Studio SP1 compiles OK
Visual Studio without Sp1 throws an error
'can't access private variable bar'

The Question is is SP1 wrong?

I don't think A.bar should be available to the nested Class C, does anyone know if the C++ spec allows this?

Thx

wc


class B;
class A 
{  
   friend class B;
   private: int bar; 
}
 
class B
{
   public:
      class C 
     {
           A myclassA;
           foo ()
           {
                    int y = myclassA.bar;  // error in pre SP1 visual studio
           }
     }
}

Open in new window

SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
BTW, which version of VS are we talking about?
Avatar of williamcampbell

ASKER

2005

So this is SP1 fix I guess.

Thx  jkr
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Here's some more info from MSDN. I may have to differ from what jkr is saying:

http://msdn.microsoft.com/en-us/library/ee6hft63(VS.80).aspx
>> The Question is is SP1 wrong?

Actually, to the letter of the C++ standard, SP1 is wrong (at least as I interpret the standard).

The standard does not say anywhere that private members of A should be accessible from a nested class C of friend class B. It only says that (obviously) friend class B (including its member functions and static data members) should have access to A's privates.

That does make sense too, since the B::C class was not declared a friend of the A class, so why should it have access to its privates ?

Consider (as a side note) that a class doesn't even have access to the privates of a nested class :
class A {
  public :
    void fun1() { class B b; b.mb; }   // OOPS : A::B::mb is private
    void fun2() { class C c; c.mc; }   // OK : A is a friend of A::C
 
  public :
    class B {
      private :
        int mb;
    };
 
    class C {
      private :
        int mc;
 
      friend class A;
    };
};

Open in new window

infinity's comment reiterates what i pointed out through my links....private members cannot be accessed anywhere outside their class other than of course by their friends
Infinity and trin

 I Agree with you that a Nested class should not be available from a friend as I asked in the question.

It appears that this was **broken** in SP1!  

jkr what do you think?

Uped the points so I can split
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
The Jury is out