Results 1 to 3 of 3

Thread: friend functions

  1. #1
    Aragorn
    Guest

    friend functions

    Hi. My question is, how do you make a function in another class friend of the class you're in?
    I mean that i can make a global function friend of a class, as:
    Code:
    class X {
       friend void friend_func(X*, int);
    private:
       int i;
    public:
       void member_func(int);
    };
    
    void friend_func(X* xptr, int a) { xptr–>i = a; }  /* this has access to X.i */
    It works if friend_func(,) does not belong to any class, but if I want to make a friend function from another class I can't make it;
    besides, i wouldn't like to make the whole class friend.

    Code:
    class X {
       friend void Y::friend_func(X*, int);
    private:
       int i;
    public:
       void member_func(int); //blah blah 
    };
    
    class Y {
    public:
       void friend_func(X*, int);
    // stuff...
    };
    I can't put Y in front of X 'cos i need X instances in Y.

    How do i gain access from Y::friend_func(...) to X? It won't work, even if i declare the class at the beginning as

    Code:
    class Y;
    class X {
       friend void Y::friend_func(X*, int);
    };
    class Y {
       void friend_func(X*, int);
    };
    neither

    Code:
    class Y {void friend_func(X*,int);};
    class X {
       friend void Y::friend_func(X*, int);
       // ... stuff... 
    };
    class Y {
       // the rest of Y here
    };
    'cause then i get multiple declaration error, and if i don't do it, i get friend_function is not a member of... although it is declared afterwards.

    any hints?
    thanks alot

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Code:
    class X;
    class Y;
    
    class X {
        friend class Y;
    
    public:
        int DoSomething() { return m_iData; }
    
    protected:
        int m_iData;
    };
    
    class Y {
    public:
        int ChangeIt(X *ptr) { ptr->m_iData++; }
    };
    Or something...
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    Aragorn
    Guest
    But then i'm making all member functions in Y friend to X, right?
    I'll do that if there's no other way, but i was looking for a method to make only one member function in Y friend to X.
    I'm getting the feeling that it is not possible.

    Thanks

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