Friend Function in C++

A friend function can access the private and protected data members and member functions of a class. It is not a member function of the class. Friend function is declared using the keyword friend. Friend function is defined outside the class scope. 

The following program shows friend function area.

#include<iostream>
using namespace std;

class rectangle {
    
    private:
    int length;
    int breadth;

    friend int area(rectangle);

};

 int area(rectangle a) {
    
    a.length = 4;
    a.breadth = 6;
    
    return a.length*a.breadth;

}

int main () {
    
    rectangle rectangularArea;
    
    cout<<"The area of the rectangle is "<<area(rectangularArea);
    
    return 0;

}

Output:

The area of the rectangle is 24
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments