/* */ Click to Join Live Class with Shankar sir Call 9798158723

What is Friends Function ?


A non-member function can access the private and protected members of a class if it is declared a friend of that class. friend function should be declared inside a class with the prefix friend. it is define outside of class like normal function without the prefix friend.

Q1.) Example of Friends Function .
    
    #include < iostream>
 
 using namespace std;
  
 class Box {
    double width;
    
    public:
       friend void printWidth( Box box );
       void setWidth( double wid );
 };
 
 // Member function definition
 void Box::setWidth( double wid ) {
    width = wid;
 }
 
 // Note: printWidth() is not a member function of any class.
 void printWidth( Box box ) {
    /* Because printWidth() is a friend of Box, it can
    directly access any member of this class */
    cout << "Width of box : " << box.width << endl;
 }
  
 // Main function for the program
 int main() {
    Box box;
  
    // set box width without member function
    box.setWidth(10.0);
    
    // Use friend function to print the wdith.
    printWidth( box );
  
    return 0;
 }

Output
Width of box : 100

Q2.) Add members of two different classes using friend functions.

#include < iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    
    public:
        // constructor to initialize numA to 12
        ClassA() : numA(12) {}
        
    private:
        int numA;
        
         // friend function declaration
         friend int add(ClassA, ClassB);
};

class ClassB {

    public:
        // constructor to initialize numB to 1
        ClassB() : numB(1) {}
    
    private:
        int numB;
 
        // friend function declaration
        friend int add(ClassA, ClassB);
};

// access members of both classes
int add(ClassA objectA, ClassB objectB) {
    return (objectA.numA + objectB.numB);
}

int main() {
    ClassA objectA;
    ClassB objectB;
    cout << "Sum: " << add(objectA, objectB);
    return 0;
}

Output
Sum: 13