ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Friend Class and Friend Function in c++ with simple example

Updated on June 14, 2016

1. Introduction

We all know that private members of the class cannot be accessed outside of the class. There is an alternative for this concept and the alternative is what called friendly functions. A friend function can access the private member of the class. Similarly, a friend class can access a private member of the class that claims the friendship.

In this hub, we will see the below concepts with examples:

  1. Creating a global friend function
  2. Creating a friend function which is actually a member function of some other class
  3. Creating a friend class.


2. Global function having friendship with a class

A global function which does not belong to any class can have a friendship with one or more class or classes. This global function will not have any constraint to access the private data member of the class. Have a look at the below example:

#include "stdafx.h"

#include <iostream>
using namespace std;

//=====================================================================
//Example 01: A Global Function having friendship with Point3d class
//=====================================================================
//Sample 01: A class to denote 3 points
class Point3d
{
private:
    int m_x;
    int m_y;
    int m_z;

public:
    Point3d(int x, int y, int z)
    {
        m_x = x;
        m_y = y;
        m_z = z;
    }

    //Sample 02: Point3d claiming Increment_point function as
    // its friend.
    friend void Increment_Point(Point3d& pt);

    //Sample 03: To print the Members
    void Printdata()
    {
        cout<<"X: "<<m_x<<endl;
        cout<<"Y: "<<m_y<<endl;
        cout<<"Z: "<<m_z<<endl;
    }
};

//Sample 04: Friend Function that makes Increment of the 3d point.
void Increment_Point(Point3d& pt)
{
    //Note that the private member of the class is changed
    //by the global function
    pt.m_x++;
    pt.m_y++;
    pt.m_z++;
}

int _tmain(int argc, _TCHAR* argv[])
{
    //Sample 05: Create the Object and print the Initial Co-Ordinates
    Point3d pt1(10,10,12);
    pt1.Printdata();
    cout<<endl;

    //Sample 06: Increment the Points using the Friend Function and print 
    // the points.
    Increment_Point(pt1);
    pt1.Printdata();
}

In the above example, the class Point3d is defined to explain the Friend Function usage. This class has three private members declared in line 13,14,15. We are going to access this private member through the global function implemented through line 39-46. Note that this function takes the Cpoint2d as a reference parameter. Also, note that the Increment_Point function is changing the x, y, z coordinates of the passed-in pt object.

Now look at the code snipped //Sample 02. Here, we specify the function Increment_Point as a friend. You can see this otherwise like, class Point2d claims that Increment_Point as its friend. Once this friendship claiming is done, the function can access the private member(s) of the class in which the friendship is claimed.

In the main function at the code snippet defined by //Sample 05, we create a Poind3d object pt1 with the coordinate values of (10,10,12). Then, the values are printed using the public member function PrintData.

In the code snippet marked by //Sample 06: The point pt1 object is passed to the Global function Increment_Point and then the data is printed. As this global function is a friend to the class Point3d, it incremented each coordinate values by 1 even though its scope is private in the object pt1.

Output

Source

3. Function of One Class Friend to Some other class

Like global function, a class member function can have a friendship with some other class. The outcome is same, that class member function can have access to the private member of the class that grants friendship. Have a look at the below example:

//=====================================================================
//Example 02: A Class having friendship with some other class member
//=====================================================================

//Sample 01: Forward Declaration as CGraphicUtil going to refer it.
class CPoint2d;

//Sample 02: CGraphicUtil class
class CGraphicUtil
{
public:
	//Sample 03: This member will be claimed as friend by the CPoint2d
	// Note that implementation is delayed.
	void MovePointbyOne(CPoint2d& pt1);

	void some_other_function()
	{
		cout<<"Does nothing";
	}
};

//Sample 04: CPoint2d class
class CPoint2d
{
private:
    int m_x;
    int m_y;

public:
    CPoint2d(int x, int y)
    {
        m_x = x;
        m_y = y;
    }

    void Print()
    {
        cout<<"X: "<<m_x<<endl;
        cout<<"Y: "<<m_y<<endl;
    }
	
	//Sample 05: CPoint2d claiming MovePointbyOne as Friend function.
	//Note the Order: CGraphicUtil layout is already defined before the 
	// CPoint2d.
	friend void CGraphicUtil::MovePointbyOne(CPoint2d& pt1); 
};


//Sample 06: We delayed this implementation intentionally.
// Now the CGraphicUtil is aware of the Layout of the CPoint2d
void CGraphicUtil::MovePointbyOne(CPoint2d &pt1) 
{
	pt1.m_x++;
	pt1.m_y++; 
}


int _tmain(int argc, _TCHAR* argv[])
{
    //Sample 07: Create a CPoint2d object and print the Co-Ordinates
	CPoint2d point(10,10);
    cout<<"Point Co-Ordinates"<<endl;
	point.Print();

	//Sample 08: Increment the Co-Ordinates using CGraphicsUtil
	cout<<endl<<"Point Co-Ordinates After Increment"<<endl;
	CGraphicUtil util;
	util.MovePointbyOne(point);
	point.Print();
}

Explanation

In this example, the member function MovePointbyOne of CGraphicUtil is claimed as a friend by the class CPoint2d. Below is the explanation for each code snippets:

Sample 01: A Forward declaration to the CPoint2d is kept. This declaration tells that CPoint2d will be defined later in the code page.

Sample 02: A class called CGraphicUtil is defined.

Sample 03: The function MovePointbyOne is declared. Note that the implementation for this function is not provided yet. This is because the compiler is not aware of the CPoint2d structure at present. And the compiler only knows that such a type exists. That is why we provided only function prototype here. Providing the implementation in the class itself will end up in the error “error C2027: use of undefined type 'CPoint2d'”

Sample 04: Defines the CPoint2d class

Sample 05: CPoint2d class claims, the member function MovePointbyOne of the class CGraphicUtil, is in friendship with it. Here one more point that you need to be aware is that the class CGraphicUtil is already defined and hence we will not get any problem.

Sample 06: Code snippet 03 provided only the declaration for the MovePointbyOne, as CPoint2d is not defined yet. Snippet 05 of the CPoint2d claimed the friendship. At this stage, we have both CGraphicUtil and CPoint2d is defined and the compiler is aware of the structure and memory requirement of both the classed. Now it is time to implement the CGraphicUtil member function MovePointbyOne as given in the //sample 06 snippet. Note that this function accepts the CPoint2d instance as a parameter and increments the private members by one.

Sample 07: A CPoint2d object called point is created with the coordinate value of 10,10. Then these coordinate values are printed using the public member function Print().

Sample 08: Creates the CGraphicUtil object called util. Then the function MovePointbyOne is called on the util object by passing the point object created in the snippet 07. The incremented coordinate values are then printed using the public member function Print.

Output

Source

Please Vote it

Did you face any Class ordering problem?

See results

4. A class granting friendship to other class

A class can grant friendship to some other class. Say, for example, if class A grants friendly access to class B, then all the member functions of class B can have access to private data members of class A. Let us see this with an example:

//====================================================================================
//Example 03: Frield Class
//====================================================================================
//Sample 01: A 2d point class defined. It claims friendship with the 
class CPoint2d
{
private:
    int m_x;
    int m_y;

public:
    CPoint2d(int x, int y)
    {
        m_x = x;
        m_y = y;
    }

    void print()
    {
        cout<<"X: "<< m_x << " Y: " << m_y << endl;
    }

    //Sample 02: Now, All the member functions of CPointUtil can access 
    // the private data of this class.
    friend class CPointUtil;
};

//Sample 03: CPointUtil changing the private data member of the supplied
// CPoint2d class.
class CPointUtil
{
public:
    void increment_x(CPoint2d& pt)
    {
        pt.m_x++;
    }

    void increment_y(CPoint2d& pt)
    {
        pt.m_y++;
    }

    void increment_both(CPoint2d& pt)
    {
        pt.m_x++;
        pt.m_y++;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    //Sample 04: Create a CPoint2d instance and print the co-ordinates
    CPoint2d pt1(5,4);
    pt1.print();

    //Sample 05: Use increment_x method to increment x coordinate
    CPointUtil putil;
    cout<<"Increment only x and print"<<endl;
    putil.increment_x(pt1);
    pt1.print();

    //Sample 06: Use increment_both to increment both x and y Co-Ordinates
    cout<<"Increment both x,y and print"<<endl;
    putil.increment_both(pt1);
    pt1.print();

}

Explanation

Sample 01: CPoint2d class is defined. This class has two private data members which represent x & y coordinate of the class.

Sample 02: Class CPoint2d specifies that CPointUtil is friend. Once this friendship is claimed, all the members of the CPointUtil can have access to the private data member of the class CPoint2d.

Sample 03: CPointUtil class has only three member functions. Each function accepts a CPoint2d class as parameter as changes the private data member. As already told, the class CPoint2d granted the friendly access to entire class CPointUtil.

Sample 04: A 2d point object named pt1 is created with the co-ordinate values of (5,4) and the co-ordinate values are printed

Sample 05: The putil object is created from the class CPointUtil. Then the member function increment_x is called by passing the pt1 as parameter. After the call, the co-ordinate values are printed.

Sample 06: Similarly the call to the function increment_both increments both x and y co-ordinate values.

Output

Source

Comments

    0 of 8192 characters used
    Post Comment

    • jabelufiroz profile image

      Firoz 3 years ago from India

      Interesting article on C++. Voted up.

    • sirama profile image
      Author

      sirama 3 years ago

      Thanks jabelufiroz.

    • profile image

      amir 3 years ago

      Why we need the constructer how to define it

    Click to Rate This Article