Friend Function Explained With Simple Example

A Friend function is a function defined outside the class, but it has access to all private and protected members of the class. To declare a friend function, it’s prototype must be declared inside the class, preceding it with keyword “friend”. For eg:

class Demo
{
    private:
        int m;
        int y;

    public:
        friend int sum (Demo d);
        void print_val ();
        Demo (int m, int y);
};

Let’s have a look at an example of friend function and it’s usage.

#include <iostream>
class Demo
{
    private:
        int m;
        int y;

    public:
        friend int sum (Demo d);
        void print_val ();
        Demo (int m, int y);
};

Demo::Demo (int x, int y): m (x), y (y)
{}

int sum (Demo d)
{
    return d.m + d.y;
}

void Demo::print_val ()
{
    std::cout << "Values are, x: " << m << " y: " << y << std::endl;
}

int main ()
{
    Demo d (10,20);
    d.print_val ();
    std::cout << "SUM: " << sum (d) << std::endl;
}

Let’s analyze the output of the above function.

Values are, x: 10 y: 20
SUM: 30

Important Points

  • These friend functions can be very useful in operator overloading.
  • These friend functions make the I/O operations easier.
  • These functions may be desirable in case of inter-related classes.
  • Derived class doesn’t inherit friend function.
  • Friend function can’t be defined as Static functions.

Friend Class

It is possible to define a whole class as a friend to other class. When a class is defined as friend to another class then it got access to all private data members and member functions.  For eg:

#include <iostream>
class Demo
{
	private:
		int m;
		int y;

	public:
		friend int sum (Demo d);
		void print_val ();
		Demo (int m, int y);
		friend class DoubleDemo;
};

class DoubleDemo
{
	public:
		void invoke ();
};

void DoubleDemo::invoke ()
{
	Demo d (10,20);
	d.print_val ();
	std::cout << "SUM: " << (d.m + d.y) << std::endl;
}

Demo::Demo (int x, int y): m (x), y (y)
{}

int sum (Demo d)
{
	return d.m + d.y;
}

void Demo::print_val ()
{
	std::cout << "Values are, x: " << m << " y: " << y << std::endl;
}

int main ()
{
	DoubleDemo d;
	d.invoke ();
}

Let’s analyze the output of above program.

Values are, x: 10 y: 20
SUM: 30

Leave a Reply

Your email address will not be published. Required fields are marked *