Friend Function/Friend class

Estimated reading: 7 minutes 40 Views

In C++, a friend function or friend class is a feature that allows a function or a class to access private and protected members of another class. This feature breaks encapsulation to some extent but can be useful in specific scenarios where tight coupling between classes is necessary or when implementing certain design patterns.

Friend Function:

A friend function is a regular function that is granted access to private and protected members of a class. To declare a function as a friend of a class, you need to declare it within the class declaration preceded by the friend keyword.

Example 1:

#include <iostream>
using namespace std;
class myClass {
        int a, b;
    public:
        myClass(int i, int j)
        {
            a = i;
            b = j;
        }
        friend int sum(myClass ob);
};
int sum(myClass ob)
{
    return ob.a + ob.b;
}
int main()
{
    myClass o(10, 20);
    cout << sum(o) << endl;
    return 0;
}

In this C++ code snippet, a class called myClass is defined with two private integer members a and b. The class also has a constructor to initialize these members. Additionally, There is a declared friend function sum inside the class.

The sum function takes an object of type myClass as its argument and returns the sum of the private members a and b of that object.

In the main function, There is an object o of type myClass with initial values of 10 and 20, and then a call to the sum function passing this object o as an argument. Finally, the output of the result of the sum function using cout.

Here’s the breakdown of the code execution:

  1. An object o of type myClass is created with values 10 and 20.
  2. The sum function is called with the object o as an argument.
  3. Inside the sum function, the private members a and b of the object ob are accessed due to the friend declaration, and their sum is returned.
  4. The returned sum is then printed using cout.

So, when you run this program, it should output:

30

Example 2:

#include <iostream>
using namespace std;
class CRectangle {
    private:
        int width, height;
        friend CRectangle duplicate(CRectangle);
    public:
        void set_values(int, int);
        int area(void)
        {
            return (width * height);
        }
};
void CRectangle::set_values(int a, int b)
{
    width = a;
    height = b;
}
CRectangle duplicate(CRectangle R)
{
    CRectangle T;
    T.width = R.width * 2;
    T.height = R.height * 2;
    return T;
}
int main()
{
    CRectangle rect, rectb;
    rect.set_values(2, 3);
    cout << "The area before duplicate = " << rect.area() << endl;
    rectb = duplicate(rect);
    cout << "The area after duplicate = " << rectb.area() << endl;
    return 0;
}

This C++ code defines a class CRectangle representing a rectangle. The class has private data members width and height, and two member functions set_values and area.

In the private section, width and height are the dimensions of the rectangle. The set_values function is used to set the values of width and height. The area function calculates and returns the area of the rectangle.

The duplicate function is declared as a friend of CRectangle. This means it has access to the private members of CRectangle.

The set_values function sets the width and height of the rectangle based on the provided parameters.

The duplicate function takes a CRectangle object as a parameter, creates a new CRectangle object T, and assigns T’s width and height to be twice that of the input R’s width and height. It then returns the new rectangle T.

In the main function:

  1. CRectangle objects rect and rectb are created.
  2. rect’s set_values function is called to set its dimensions to 2×3.
  3. The area of rect before duplication is printed.
  4. duplicate function is called with rect as an argument, and the returned rectangle is assigned to rectb.
  5. The area of rectb after duplication is printed.

The output of this program will be:

The area before duplicate = 6
The area after duplicate = 24

Example 3:

#include <iostream>
using namespace std;
class Tri;
class CRectangle {
        int width, height;
    public:
        void set_values(int a, int b) {
            width = a;
            height = b;
        }
        friend int Sum(Tri T, CRectangle R);
};
class Tri {
        int W, H;
    public:
        Tri(int a, int b)
        {
            W = a;
            H = b;
        }
        friend int Sum(Tri T, CRectangle R);
};
int Sum(Tri T, CRectangle R)
{
    return T.W + R.width;
}
int main()
{
    CRectangle r;
    r.set_values(2, 3);
    Tri l(5, 10);
    cout << Sum(l, r) << endl;
    return 0;
}

This C++ code demonstrates the usage of friend functions across different classes. Here’s a breakdown of the code:

Class Declarations:

  • Two classes are declared: CRectangle and Tri.
  • CRectangle has two private data members width and height, and a member function set_values to set these values.
  • Tri has two private data members W and H, and a constructor to initialize them.

Friend Function Declaration:

  • Both classes declare a friend function named Sum. This means that Sum function can access the private members of both CRectangle and Tri.

Friend Function Implementation:

  • The Sum function takes objects of types Tri and CRectangle as arguments and returns the sum of their corresponding private members.
  • In this case, it returns the sum of W from the Tri object and width from the CRectangle object.

Main Function:

  • In the main function, an object r of type CRectangle is created and its set_values function is called to set its dimensions to 2×3.
  • Another object l of type Tri is created with dimensions 5×10.
  • The Sum function is called with objects l and r as arguments, and the result is printed.

Output:

  • Since the Sum function returns the sum of W from Tri and width from CRectangle, the output would be 5 + 2 = 7.

Friend Class:

Friend class is a class that is granted access to the private and protected members of another class. You declare a friend class by preceding its declaration with the friend keyword inside the class that it’s a friend of.

Example 4:

#include <iostream>
using namespace std;
class CSquare;
class CRectangle {
        int width, height;
    public:
        int area(void) {
            return (width * height);
        }
        void convert(CSquare);
};
class CSquare {
    private:
        int side;
    public:
        void set_side(int x)
        {
            side = x;
        }
        friend class CRectangle;
};
void CRectangle::convert(CSquare a)
{
    width = a.side;
    height = a.side;
}
int main()
{
    CSquare sqr;
    CRectangle rect;
    sqr.set_side(4);
    rect.convert(sqr);
    cout << rect.area() << endl;
    return 0;
}

This C++ code demonstrates the usage of friend classes and member functions, particularly in the context of a CRectangle class and a CSquare class.

Class Declarations:

  • Two classes are declared: CRectangle and CSquare.
  • CRectangle has two private data members width and height, and a member function area to calculate its area. It also has a member function convert, which is later defined outside the class.
  • CSquare has one private data member side and a member function set_side to set its value. It declares CRectangle as a friend class.

Friend Class Declaration:

  • CSquare declares CRectangle as a friend class, allowing CRectangle to access its private members.

Member Function Definition:

  • The convert member function of CRectangle is defined outside of the class.
  • It takes a CSquare object as a parameter and assigns its side to both width and height of the CRectangle.

Main Function:

  • In the main function, objects sqr of type CSquare and rect of type CRectangle are created.
  • set_side function of sqr sets its side to 4.
  • convert function of rect is called with sqr as an argument, converting the square into a rectangle.
  • The area of the resulting rect is then printed.

Output:

  • Since the side of the square is 4, after converting it to a rectangle, both width and height of the rectangle become 4. Therefore, the area of the resulting rectangle is 4 * 4 = 16.
Share this

Friend Function/Friend class

Or copy link

CONTENTS
English