Can 2 classes share a friend function?
Asked Answered
B

4

7

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?

Beseech answered 23/8, 2013 at 13:38 Comment(3)
Yes it is possible. Yes, f1() would have access to members of both classes.Concertmaster
Have you tried compiling a simple example? This seems like it would be easy to test.Teacup
What makes you think this would not be possible?Cypro
K
19

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!

Kora answered 23/8, 2013 at 18:14 Comment(1)
Thank you very much man ur example was very nice and easy to understandBeseech
G
1

There is no restriction on what function can or cannot be friends's of class's, so yes there's no problem with this.

Georgetta answered 23/8, 2013 at 13:44 Comment(1)
Well, you have to be able to name the function, but that's a natural restriction. E.g. struct { static void foo(); }; or functions in anonymous namespaces in other translation units.Fusco
A
1

correction to the above code

#include<iostream>
using namespace std;
class B;                   //defined later
class A;                  //correction (A also need be specified)
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;
}
Austrasia answered 22/1, 2014 at 12:15 Comment(0)
S
-2
#include<iostream>

using namespace std;

class first
{
    friend void getdata(first object1, int i);
};

class second
{
    friend void getdata(second object2, int j);
};

getdata(first object1, int i, second object2, int j)
{
    cout<<i+j;
}

main()
{
    first object1;
    second object2;
    getdata(object1, 5, object2, 7);
}
Shifty answered 5/5, 2017 at 17:31 Comment(1)
friends functions are intended to have access to classes private membersWaken

© 2022 - 2024 — McMap. All rights reserved.