Topic :Friend Keyword concept In C++: Friend Function | Friend Class

The Friend Concept:

Encapsulation and Data hiding are two Primary features of Object-Oriented Programs. we use encapsulation when we place data and functions together in a capsule as objects. We use data hiding when we create Private class members, so No function can access these private members from outside the class. In our previous Tutorial, we took advantages of data hiding. Once we create a class, with the private keyword, NO function could ever modify or use the private member data in our class from outside. Only the functions that are part of a class can access the class private data. This approach ensures that all data members are used correctly and appropriately.

Sometimes, however, it is convenient to allow an outside, non-member function to have access to a private data member. For example, We might have a class that stores data, and a function or another class that displays the data on the screen. Although the storage class and display code have been separated for easier maintenance, the display code is really intimately tied to the details of the storage class. Consequently, there isn't much to gain by hiding the storage classes details from the display code.

In this Situations, there are two options:


Have The Display code use the publicly exposed functions of the storage class. However, this has several Potential downsides. First, these public member functions have to be defined, which will take time, and can clutter up the interface of the storage class. Second, the storage class may have to expose functions for the display code that it doesn't really want accessible to anybody else. There is no way to say "This Function is meant to be used by the display class only".


Alternatively, using friend classes and friend functions, we can give our display code access to the private details of the storage class. This lets the display code directly access all the private members and functions of the storage class while keeping everyone else out. in this tutorial we'll take a closer look at how this is done.



Friend Function:

A Friend Function is a function that can access the Non-Public Members (Private & Protected) of a class, even though the function itself is not a member of the class. A Friend function is a normal function with special access Privileges.



Non-Public members of a class include all Private and protected data fields and functions. we already discussed about private and protected members in our previous tutorials.



In our own relationships, We often give our friend access to private Information that we don't want the outside world to know. like, i can allow my friend to use my computer, or tell my friend about my salary, or provide my friend with embarrassing details of my high school days. in a similar way, a C++ function or class that is a Friend has access to the private information in a class.

In order to allow an external function to have access to the Private and Protected members of a class we have to declare the prototype of the external function that will gain access preceded by the keyword friend within the class declaration that shares its members. The basic Syntax to Declared Friend Function is:


friend Return_type Function_name(class_name);


In above syntax, Friend is the keyword used to declare Friend function, Return_type could be any data type.



class SUM
{
    friend void Access(SUM); //friend Function prototype declared.
 
    private: 
        int a;
 
    public:
        SUM(){a=10;} //constructor.
};


In the above example, we've declared a function named Access() , This function is not a member of the class SUM , so Normally Access() Would not be able to Access the private members of Class SUM. However, because SUM has specifically declared this Access() Function to be a friend of the Class, the Access() function is given access to private members of SUM. Lets have a look at complete Example:



/* Friend Function Example: InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class SUM //Class Begin.
{
    friend void Access(SUM); //friend Function Prototype Declared.
    private: 
 
//Its private member, but our Friend function can Access this Member.
    int a; 
 
    public:
        SUM(){a=10;} //constructor.
};
 
void Access(SUM obj) //Friend Function definition.
{
    obj.a=obj.a+30; //Access & modify Private data Using Object "obj".
    cout<<" The Value of A is "<<obj.a;
}
 
main()
{
    SUM Obj; //object Create.
    Access(Obj); //Calling Of Friend Function.	
 
    return 0;
}


In The Above Simple Example, we have declared A Friend Function Prototype in Class SUM Body, and define Class outside the body. The function Access() is not the member of class. Note That We have to Pass an SUM Object to Access(). This is because Access() is not a member function. So we need to pass an object of Class SUM to Function Access() as parameter.

A Function Can Be a Friend Of more than one Class at the same time. We need to use this Syntax for Multiple Friendship:


friend Return_type Function_name(class_name1, class_name2);


In Above Syntax, Friend is the keyword used to declare Friend function, Return_type could be any data type. Consider the following example:


/*Friend Function can access multiple classes: InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class B; //Class B Prototype: (its important).
class A // Class A Begin:
{
//Friend Function Prototype, This function will access both classes A & B.
    friend void Add(A,B); 
 
    private: //Private Data: We Need to Access This Data:
        int a;
 
    public:
        A(){a=0;} //constructor.
 
};
 
class B // Class B definition Begin:
{
//Friend function prototype.
    friend void Add(A,B); 
 
    private: //Private Data: We Need to Access This Data: 
        int b;
 
    public:
        B(){b=0;} //constructor.   
};
 
 
//Friend Function Defination:
void Add(A ob1, B ob2)
{
    ob1.a=10; //Assign Value to Class A Private Member.
    ob2.b=5;  //Assign Value to Class B Private Member.
 
    cout<<" The Value Of A is "<<ob1.a<<endl;
    cout<<" The Value Of B is "<<ob2.b<<endl;
 
    cout<<" The Sum is: "<<ob1.a+ob2.b<<endl;
}
 
main()
{
    A OBJ1; //Class A object.
    B OBj2; //Class B object.
    Add(OBJ1, OBj2); //Friend function Calling:
 
    return 0;
}


So by Using Same Syntax, we can create a Friend Function That can Access Multiple Classes.



It's important to declare class prototype at the top. because when we will use class name in friend function parameter, the compiler will generate an error, that Class name not declared. so it's important to declare class prototype at the top:


Friend Class:

Just as we have the possibility to define a friend function, it is also possible to make an entire class a friend of another class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined. The basic Syntax to make class friend is :


friend class class-name;

In Above syntax, Friend and Class is the keyword, and Class_name could be any class that already exists, if the class doesn't exist, then we must use the prototype of that class at the top of Friend class. As shown in this example below:



/*Friend Class: InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class A;  //class A prototype:
class B  //Class B begin:
{
    friend class A; //Friend Class Declaration:
    private:
        int Y; //Private member, need to access this member:
 
    public:
        B(){ Y=0;} //constructor:
};
 
class A //Class A definition:
{
    private:
        int X; //Private member:
 
    public:
     A(){X=10;}     //constructor:
 
     void add(B obj) //function with Class B and its Object as an parameter:
     {
         obj.Y=25; //Class B private member Access:
         cout<<obj.Y<< " + "<<X<<" = "<<obj.Y+X<<endl;
     }
};
 
 
main()
{
    A Obj1; //class A object:
    B Obj2; //Class B object:
 
/*now we need to call Function using Class A object:
  and this function need class B object as an parameter.*/
    Obj1.add(Obj2); 
 
    return 0;
}


In the Above Example, We started with the prototype of Class B. as we know that it's important to declared class prototype because Compiler compiles the code line by line from top to bottom. so when compiler will about to compile the code line (friend class A;) , it will generate an error (i.e. "A" Was not declared ) , because compiler don't know what is This "A" & where is its definition, so when we will declared an Class prototype at the top, then compiler will know about class "A". so its important.

In Above Example there is a simple example of class friends, we just took one number from one class, the second number from another class, and add them. It looks like easy, and useless that why we took one number from one class and second from other, as we can do same in just one class, yes we can, but it's just an example. Incoming Tutorials we will see that how this friend function and class can make our life easy. for now its all about to clear your concept regarding Friends.



However, extensive use of Friend techniques diffuses the concept of Data encapsulation and Data Hiding. Allowing external functions to manipulate internal data can lead to inconsistency, especially if a class is modified or extended in a later version. For this reason, we should take special care when using friend techniques.











I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement