C++ Friend function and Friend class

In the last C++ programming tutorial we looked at inheritance. In this C++ programming tutorial we will take a look at C++ friendship.

Friend Functions

A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading.

In the following example, the friend function print is a member of class TWO and accesses the private data members a and b of class ONE.


#include <iostream>
using namespace std;

//Must be known to TWO
//before declaration of ONE.
class ONE;

class TWO
{
public:
  void print(ONE& x);
};

class ONE
{
  int a, b;
  friend void TWO::print(ONE& x);
public:
  ONE() : a(1), b(2) { }
};

void TWO::print(ONE& x)
{
  cout << "a is " << x.a << endl;
  cout << "b is " << x.b << endl;
}

int main()
{
  ONE xobj;
  TWO yobj;
  yobj.print(xobj);
}

Friend functions have the following properties:

  • 1) Friend of the class can be member of some other class.
  • 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND.
  • 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.
  • 4) Friends are non-members hence do not get “this” pointer.
  • 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes.
  • 6) Friend can be declared anywhere (in public, protected or private section) in the class.

Friend Class

A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).


#include <iostream>
using namespace std;

class MyClass
{
	// Declare a friend class
	friend class SecondClass;

	public:
		MyClass() : Secret(0){}
		void printMember()
		{
			cout << Secret << endl;
		}
	private:
		int Secret;
};

class SecondClass
{
	public:
		void change( MyClass& yourclass, int x )
		{
			yourclass.Secret = x;
		}
};

void main()
{
	MyClass my_class;
	SecondClass sec_class;
	my_class.printMember();
	sec_class.change( my_class, 5 );
	my_class.printMember();
}

Note:we declared friend class SecondClass; in the class MyClass, so we can access Secret in the class SecondClass.

Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.

That is all for this tutorial.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 37 responses to “C++ Friend function and Friend class”

Why not let us know what you think by adding your own comment!

  1. karan on March 15th, 2010:

    hi , can u give me the difference between the friend class and friend function….

  2. admin on March 15th, 2010:

    The tutorial is clear on this, but here you go, I found this definition on another site:

    A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. A friend class has full access of private data members of another class without being member of that class.

  3. shrihari on June 28th, 2010:

    can two functions be declared friend to one class?

  4. admin on June 29th, 2010:

    @shrihari Sure you can declare two functions friend of one class, take a look at an example:

    #include<iostream>
    using namespace std;

    class AClass {
    private:
    int a,b;
    public:
    void test() {
    a=10;
    b=20;
    }
    // Declare the two functions friends.
    friend int add(AClass input);
    friend int minus(AClass input);
    };

    // Function one
    int add(AClass input) {
    return int(input.a + input.b);
    }

    // Function two
    int minus(AClass input) {
    return int(input.b – input.a);
    }

    void main(void){
    AClass output;
    // Initialize output
    output.test();
    cout << add(output) << endl;
    cout << minus(output) << endl;
    }

    I hope this answers your question.

  5. shrihari on June 30th, 2010:

    Thank u. It works!!

  6. hemed on May 18th, 2011:

    why the argument or parameter of a friend function must be of the type of Aclass
    eg from the code above
    // Declare the two functions friends.
    friend int add(AClass input);
    friend int minus(AClass input);

    am confused with this please help me

  7. silu on June 13th, 2011:

    friend function can access the private members of class. Is it possible, so that friend function should not access the private members of a class? Is any concept deals with it.

  8. Yash Bawne on September 24th, 2011:

    We consider that friend function access the private data member of the class.But I did’nt get actually ,because member function of the class also use private data directly.
    Plese clarify that…

  9. veena bopche on November 9th, 2011:

    can we make more than one friend functions within a class?

  10. tek on December 2nd, 2011:

    C++ :Can we access private function of class from another class(not friend or inherited) without using public function?I mean Class A has private function A1.Can we access A1 from another class B directly using pointer.You cannot use public function in class A to return address of private function A1.class B is not friend or child of class A.
    -Tek

  11. SHAGUN on January 17th, 2012:

    worth!!!!!!!!!!!

  12. Reshma on February 8th, 2012:

    wat is the output for the program friend class… :-|

  13. elite leena on February 24th, 2012:

    @reshma
    the output is
    0
    and
    5

  14. Sateesh Kumar on September 1st, 2012:

    This is helpful to all who need this.

  15. bhanawrlal on September 10th, 2012:

    this is not helpfull for me i want to see syntax of friend function

  16. deepali on October 6th, 2012:

    Well Explained, good concept !!

  17. Anuj on November 6th, 2012:

    Hey!
    Can i pass an object to friend function? (of the same class whose friend the function is)

    can a member function call this friend function? (if it does accept a class argument)

  18. Shailesh on November 20th, 2012:

    Characteristics of friend function

    1. The friend function can access private and protected data members.
    2. Friend function cannot call with the help of Object of that class, it is call by using normal ‘C’ function.
    3. Generally, friend function can take Object as a argument.
    4. Friend function is not in scope of class.

  19. Awet(success) on December 21st, 2012:

    wow it is fantastic so continue…….

  20. syra on January 7th, 2013:

    nyc explanation!!!

  21. radhika obhan on January 7th, 2013:

    can u show a program in which we can make use of friendly function using two classes to calculate area of two objects using any fake formula

  22. VinC on March 6th, 2013:

    class square
    {
    int side;

    square(int a)
    {
    side = a;
    }
    friend int area(square sqObj);
    };

    class rect
    {
    int len, bre;
    rect (int a, int b)
    {
    len = a;
    bre = b;
    }

    friend int area1(rect recObj);
    }

    int area (square sqObj)
    {
    return(sqObj.side*sqObj.side);
    }

    int area1 (rect rectObj)
    {
    return(rectObj.len*rectObj.bre);
    }

    void main()
    {
    square sq(5);
    rect rec(3,5);
    cout << area(sq);
    cout << area1(rec);

    }

  23. Dharmendra Kumar on April 26th, 2013:

    A friend function can define also inside the class. then what is the make difference b/w if i defining a friend function inside a class and outside a class.

  24. Khurram on July 19th, 2013:

    What is principle of friendship in the context of functions and classes?

  25. reshma on August 10th, 2013:

    can any1 give me a pgm fo class private data modifying with a friend function

  26. keerthana on September 25th, 2013:

    hey guys…i cant get the difference b/w friend function and friend class..
    wht s the use of friend function if we declare public also we can access private data know.
    there is no clear information on this topic.

  27. bhushan on October 2nd, 2013:

    tnx admin..

  28. Aniket on October 16th, 2013:

    Write a normal function which adds objects of the complex number class. Declare this normal function as friend of complex class

  29. Aniket on October 16th, 2013:

    Can u plz giv a program to read two integer numbers through two different objects of class ‘Addition’. Add these two integers using friend function and display the total.

  30. Mithilesh on November 6th, 2013:

    Can i declare two different classes and then access their objects with friend function
    //for example//

    class real
    {
    public:
    void values()
    {
    }

    };
    class img
    {

    public:
    void values()
    {
    }

    };

    int add(real r1.values(),img i1.values()
    {
    //addition is done here//
    ]

    Can this Happen??

  31. Jomiloju on January 17th, 2014:

    I’m replying to mithilesh’s post,

    With my understanding from the information passed in the above post, we can declare a function to be friends with one or more classes.

    This in turn means we can access the private members which in your example ( although poorly described ) would be the data members.
    When this function is to be called in the main program.
    It would be called without the dot operator as it isn’t a member of any class. This therefore suggests that all friends to multiples classes must take on the same name and must take arguments of all these classes. Therefore we pass each class as an argument and access the data members.

    In your example I’m guessing add is the friend function.

    Int add ( const real& r1,const img i1)
    {
    Return ( R1.rvalue + i1.imag ); /
    }

  32. ASIF on February 23rd, 2014:

    is it possible for a friend function to be a member of one class but friend to another class in c++??

  33. dhruvin patel on March 3rd, 2014:

    wht is the code to find the average value4 of two numbers using friend function??????????

  34. sahil gupta on March 7th, 2014:

    @ dhruvin patel the following code is the solution of your problem” wht is the code to find the average value4 of two numbers using friend function??????????”

    code is::

    #include
    #include
    class two;
    class one
    {
    int a;

    public: void setvalve(int x)
    {
    a=x;
    }

    friend void avg(one n, two m);
    };

    class two
    {
    int b;

    public:
    void setvalve(int x)
    {
    b=x;
    }
    friend void avg(one n, two m);
    };

    int main()
    {

    one a1;
    two a2;
    int a,b;
    cout<>a>>b;

    a1.setvalve(a);
    a2.setvalve(b);
    avg(a1,a2);
    getch();
    return 0;
    }
    void avg(one n, two m)
    {
    float avg;
    avg= (n.a+m.b)/2;
    cout<<avg<< "is avrage";
    }

  35. swati on March 11th, 2014:

    Is it possible to put the sum of objects of two different classes into an object of third class?if yes then plz tell how with an example

  36. Jomiloju on March 17th, 2014:

    Reply to @ASIF’s and @Swati’s post
    ————————————————————————————–
    @ASIF :
    ——

    C++ supports multiple friendship. This means you can declare a function/class to be friends with more than one class. However you must first understand that a FRIEND FUNCTION/CLASS is NOT a member of the class/classes to which it is friends with.

    A friend function or a friend class is a normal function / class that has been explicitly granted access to the private members of a class. You must therefore then treat it as a normal function and pass as an argument the class/classes it is friends with.

    E.g friend int function_to_add( const class_one &one , const class_two &two )
    {
    return ( one.private_data_member + two.private_data_member )
    }

    Hope my answer would suffice :)

    ————————————————————————————
    @SWATI:
    ——
    “Is it possible to put the sum of objects of two different classes into an object of third class?if yes then plz tell how with an example ? ”

    As it is most programming tasks there’s usually more than one way of getting the job done. In this case you have the option of either using a friend class or not using friendship at all. Personally I would opt for the latter.

    PsuedoCode : without a friend class

    Class A
    {
    int i;

    public:
    A (int input ) : i=input ; // constructor
    int get_i (){ return i; } //member function that returns i

    }

    Class B
    {
    int j;

    public:
    B(int input ) : j=input ; // constructor
    int get_j (){ return j; } //member function that returns j

    }

    Class C
    {
    int k;

    public:
    C(int input ) : j=input ; // normal constructor

    C( A &a_ ,B &b ) : k = a_.get_i + b_get_j {} // constructor #2

    void set_k_to_sum_of_A_and_B ( const A& a_ , const B &b_ )
    {
    k = a_.get_i() + b_.get_j() ;
    }

    }

    The function set_k_to_sum_of_A_and_B does the summation for you
    and if you wanted to perform the summation at instantiation of an object of type C then the constructor #2 does this too.

    I really do hope this helps :)

    if you want an example illustrating how to get this done with the friend class then let me know via a comment.

    Jomiloju.

  37. Muhamad Asif Ali Muhavia on May 9th, 2014:

    eg of friend class,,

    class a
    {
    private:
    int a,b;
    public:
    void show()
    { cout<<""a=<a<<"b="<<b;
    }
    friend void(show1,show2)
    };
    class b
    {
    public:
    show2()
    {a=10;
    b=20;
    }
    };
    void main()
    {
    clrscr();
    a obj1;
    b obj2;
    obj1.show1();
    }