Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 2 classes share a friend function?

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?

like image 840
user2236974 Avatar asked Aug 23 '13 13:08

user2236974


People also ask

Can two classes be friends in C++?

A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private members of another class.

How do you bridge two classes using a friend function?

So this can use even the private variables "a,b" of the class "friendcl". The function "sum" is not a member of any class. The "x" is an object of the class "friendcl" function, which is declared in the friend function to pass arguments. Thus, a bridge between two classes, i.e. "sum" and "friendcl" can be established.

Can function of one class be a friend of another class?

Functions declared with the friend specifier in a class member list are called friend functions of that class. Classes declared with the friend specifier in the member list of another class are called friend classes of that class.

Can a class inherit friend function?

No. You cannot inherited friend function in C++. It is strictly one-one relationship between two classes. Friendship is neither inherited nor transitive.


3 Answers

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!

like image 96
iluvthee07 Avatar answered Oct 17 '22 15:10

iluvthee07


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

like image 45
Paul Evans Avatar answered Oct 17 '22 16:10

Paul Evans


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;
}
like image 24
SDL_Developer Avatar answered Oct 17 '22 17:10

SDL_Developer