Friend functions error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JavierL
    New Member
    • Apr 2010
    • 17

    #1

    Friend functions error

    Im doing an excercise, where i need to use a friend class and a friend function from another class to access a private member of a third class. With the 'friend class' everything when OK, but i have problems with the friend funcion, it would be very helpful if someone could see what's wrong because i cant, and im really stucked with this.

    Code:
    // C5_TP3.cpp : main project file.
    
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <conio.h>  // for _getche(), VS 2010 closes the cmd >_<
    
    
    using namespace System;
    using namespace std;
    
    class A; // for refering to A* in class C
    
    class C {
        void i(A*);
    };
    
    class A {
    public :
        friend class B; // Friend class B
        friend void C::i(A*); // Friend function from C, this is what is giving me issues
    private:
        string a;
    };
    
    class B{
    public:
        void a(A* x);
    };
    
    void B::a(A* x){
        x->a= "Reporting in B friend";
        cout << x->a << endl;
        _getche();
    }
    
    void C::i(A* k){
        k->a = "Reporting in C friend";
        cout << k->a << endl;
        _getche();
    }
    
    int main(array<System::String ^> ^args)
    {
        A z; B b; C c;
        b.a(&z);
        c.i(&z);
        return 0;
    }
    Here is the output error from vs 2010:

    1>C5_TP3.cpp(22 ): error C2248: 'C::i' : cannot access private member declared in class 'C'
    1> C5_TP3.cpp(16) : see declaration of 'C::i'
    1> C5_TP3.cpp(15) : see declaration of 'C'
    1>C5_TP3.cpp(53 ): error C2248: 'C::i' : cannot access private member declared in class 'C'
    1> C5_TP3.cpp(16) : see declaration of 'C::i'
    1> C5_TP3.cpp(15) : see declaration of 'C'
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    I don't think that you can access some private member x::p of a class X by declaring X and/or X::p your friend. Another way - make X access your private function by declaring X your friend - yes.

    Comment

    • hype261
      New Member
      • Apr 2010
      • 207

      #3
      Your errors are not due to the friend function. Your errors are due to your class C

      Code:
      class C 
      { 
          void i(A*); 
      };
      C++ defaults to private scope for classes. So when you call c.i(&z); in your main function it is giving you an error.

      Change code to

      Code:
      class C
      {
      public:
      void i(A*);
      };

      Comment

      • JavierL
        New Member
        • Apr 2010
        • 17

        #4
        Yes! I knew it was something dull that I was missing, thank you, very much.

        Comment

        Working...