Creating Friend Class instance in Function parameters

319 views Asked by At

I am new to working with C++. I need to declare an instance of a class as the parameter of a function in another class, with the parameter instance declared as a friend. I illustrate with an example.

class foo(){
    private:
        void a(){
          // function definition
                }
}

class other_foo(){
    public:
         void b(foo f){
             // function definition
                 }

}

In the above example I need to declare class other_foo as a friend for foo so that I can use foo class' private function "a". I have read on a number of other references but there is no definitive guide as to whether it is really possible or not. If not, could you please suggest a workaround? I tried to declare other_foo as friend in class foo definition but the compiler threw an error with other_foo that private methods are not accessible. I have also tried declaring the instance as "friend foo f" in the parameter itself but the compiler threw an error for that. Where do I actually need to declare that class other_foo is a friend class for class foo?

1

There are 1 answers

0
Ediac On
class foo{
private:
    void a(){
      // function definition
    }
    friend class other_foo;
};

class other_foo{
public:
     void b(foo f){
         // function definition
     }
};

Now other_foo can access foo's private members. The parentheses in front of class' name were unnecessary, and added ; after class definition.