Search code examples
c++friend

How to access private member function using friend class object?


In main, I want to access the display function. Here, in class B I declared class A as friend. So i thought that it is possible to access the private member functions. But i dont know how to do that.

#include<stdio.h>

class A
{ 
  public:
  class B
  {
    public:
     friend class A;
    private:
     void display()
     {
       printf("\nHi");
     }
  };
};

int main()
{
  //here i wanna access display function.. is it possible?
  return 1;
}

Solution

  • friend specifies what has access to private members. In your case, you want to access private members in the main function, so you should specify that it's friend:

    class A
    { 
        public:
        class B
        {
           friend int main();
           void display()
           {
               printf("\nHi");
           }
        };
    };
    
    int main()
    {
        // here you can access display function:
        A::B object;
        object.display();
    }
    

    Alternatively, if you want to make class A (and not anything else) a friend, then class A should access the display function. Any member of class A can do it:

    class A
    { 
        public:
        class B
        {
           friend class A;
           void display()
           {
               printf("\nHi");
           }
        };
    
        // here you can access display function:
        void access_display(B object)
        {
            object.display();
        }
    };
    
    int main()
    {
        A object1;
        A::B object2;
        object1.access_display(object2);
    }