CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Friend classes

  1. #1
    Join Date
    Oct 2009
    Location
    NY, USA
    Posts
    191

    Friend classes

    I thought friend classes were able to access the private and protected members. So, in the following test example why am I am not able to write something like:
    Code:
    A a1;
    int p = 15;
    cout<<a1.function13(p)
    Code:
    class A
    {
    public:
    	int function1(int x) { return 2*x; }
    };
    
    class B
    {
    public:
    	double function13(int x) { return x/2; }
    	friend class A;
    };

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: Friend classes

    The fact that A is a friend of B doesn't change the fact that A has no member function named function13().

    You could, however, do this for instance:

    Code:
    class A
    {
    public:
      A() : secret(666) {}
    
      int function1(int x) { return 2*x; }
    
      friend class B;
    
    private:
      int secret;
    };
    
    class B
    {
    public:
      double function13(int x) { return x/2; }
      void traitor()
      {
        std::cout << "a_member's secret is " << a_member.secret << std::endl;
      }
    
    private:
      A a_member;
    };
    Last edited by Eri523; November 7th, 2010 at 06:47 PM. Reason: Corrected code
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: Friend classes

    I thought friend classes were able to access the private and protected members
    The 'friend' keyword should be avoided at all times. As soon as you need it, it means you have a design flaw.

  4. #4
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: Friend classes

    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured