Can 2 classes share a friend function?

user2236974 picture user2236974 · Aug 23, 2013 · Viewed 14.7k times · Source

Today i have a doubt regarding friend function. Can two classes have same friend function? Say example friend void f1(); declared in class A and class B. Is this possible? If so, can a function f1() can access the members of two classes?

Answer

iluvthee07 picture iluvthee07 · Aug 23, 2013

An example will explain this best:

class B;                   //defined later

void add(A,B);

class A{
    private:
    int a;
    public:
    A(){ 
        a = 100;
    }
    friend void add(A,B);
};   

class B{
    private:
    int b;
    public:
    B(){ 
        b = 100;
    }
    friend void add(A,B);
};

void add (A Aobj, B Bobj){
    cout << (Aobj.a + Bobj.b);
}

main(){
    A A1;
    B B1;
    add(A1,B1);
    return 0;
}

Hope this helps!