Search code examples
c++objectfriendprivate-members

Function of one class friend of another class


I have two classes X and Y.

Y has a private member mark, X has a function getmark().
I declared getmark() as a friend of Y.

Now, how do I access the private member mark of Y using the friend function?

This is the code I have so far

#include<iostream>

using namespace std;

class X
{
    public:
    int getmark();
};

class Y
{
    int mark;
    public:
    friend int X::getmark();
};

int main()
{

}

Solution

  • #include<iostream>
    
    using namespace std;   
    
    class Y; //forward declaration of class Y
    class X
    {
        public:
        int getmark(Y);
    };
    
    class Y
    {   
        int mark;
        public:
        friend int X::getmark(Y);
    };
    
    int X::getmark(Y obj){
        cin>>obj.mark;
    }
    
    int main()
    {
      X a;  
      Y b;
      a.getmark(b);
    }
    

    At first, when the object a (class X) is created, a forward declaration of class Y is necessary in order to declare the Y argument to X::getmark().

    Creating object b (class Y) wont be a problem as the compiler knows class X exists (for the friend function).

    Then, simply call the function getmark() through the object a.

    Note: It is necessary to declare the function getmark() after the declaration of class Y, or else compiler will consider the class Y as an incomplete type.