Vous êtes sur la page 1sur 7

01/08/13

Friend Class and Friend Function Examples in C++

Friend Class and Friend Function


Examples in C++

by sirama
1 Follow er

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 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 belongs to any class can have friendship with one
or more class or classes. This global function will not have any restriction to
access the private data member of the class. Have a look at the below example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#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;

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

1/7

01/08/13

Friend Class and Friend Function Examples in C++

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

};

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 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 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.
The main function at code snippet defined by //Sample 05, we create a Poind3d
object pt1 with the co-ordinate 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 friend to the class Point3d, it incremented each co-ordinate values by 1
even though its scope is private in the object pt1.

Output

Source: Author

3. Function of One Class Friend to Some other class


sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

2/7

01/08/13

Friend Class and Friend Function Examples in C++

Like global function, a class member function can have friendship with some other
class. The effect 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

//=====================================================?
================
//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();

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

3/7

01/08/13

Friend Class and Friend Function Examples in C++

64
65
66
67
68
69
70

//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 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 parameter and increments the private members
by one.
Sample 07: A CPoint2d object called point is created with the co-ordinate value of
10,10. Then these co-ordinate 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 co-ordinate values are then printed using the
public member function Print.

Output

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

4/7

01/08/13

Friend Class and Friend Function Examples in C++

Source: Author

Please Vote it
Did you face any Class ordering problem?
See results without voting

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

?=
//========================================================
==========================
//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();

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

5/7

01/08/13

Friend Class and Friend Function Examples in C++

56
57
58
59
60
61
62
63
64
65
66
67
68

//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 represents x and y co-ordinate 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: Author

Quiz

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

6/7

01/08/13

Friend Class and Friend Function Examples in C++

view quiz statistics

This Hub was last updated on July 23, 2013

sirama.hubpages.com/hub/Friend-Class-and-Friend-Function-Examples-in-C

7/7

Vous aimerez peut-être aussi