Friday, March 12, 2021

, , , , ,

Friend function in C++ with example program

Well hiding the data is core of  object-oriented programming but friend function in C++ is an exception which break the rule of OOP's.

friend function and friend classes in C++ programming helps to give the access member functions from outside the class.

or in the other words the protected and private data of a class can be accessed with the help of function in C++.

Declare friend function in C++

 friend function can access the private and protected it should be declare with the the friend keyword.

 

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

 Example program to understand Working of friend Function

 

// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
    private:
        int meter;
        
        // friend function
        friend int addFive(Distance);

    public:
        Distance() : meter(0) {}
        
};

// friend function definition
int addFive(Distance d) {

    //accessing private members from the friend function
    d.meter += 5;
    return d.meter;
}

int main() {
    Distance D;
    cout << "Distance: " << addFive(D);
    return 0;
}

As you can see here, addFive() in upper example is a friend function that can access both the private and public data members.

 friend Class in C++

 friend class can be used in c++ programming with friend keyword.

class ClassB;

class ClassA {
   // ClassB is a friend class of ClassA
   friend class ClassB;
   ... .. ...
}

class ClassB {
   ... .. ...
}

 if a class is declared a friend class in c++ programming then all the member functions of newly become friend class become friend functions.

See in the upper example  ClassB is a friend class so we can access all members of ClassA from inside ClassB.

 But we can't access members of ClassB from inside ClassA. 

Example program for C++ friend Class


// C++ program to demonstrate the working of friend class

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
    private:
        int numA;

        // friend class declaration
        friend class ClassB;

    public:
        // constructor to initialize numA to 12
        ClassA() : numA(12) {}
};

class ClassB {
    private:
        int numB;

    public:
        // constructor to initialize numB to 1
        ClassB() : numB(1) {}
    
    // member function to add numA
    // from ClassA and numB from ClassB
    int add() {
        ClassA objectA;
        return objectA.numA + numB;
    }
};

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


0 comments:

Post a Comment