You get a bonus - 1 coin for daily activity. Now you have 1 coin

1.7. Friends of classes 1.7.1. Friendly function

Lecture



A friendly function is a function that, while not being a component of a class, has access to its protected and own components. Such a function should be described in the body of the class with the friend specifier.

Example 1.7.1

Example 1.7.1

class myclass

{

int x, y;

friend void set (myclass *, int, int);

public:

myclass (int x1, int y1) {x = x1; y = y1;}

int sum (void) {return (x + y);}

};

 

void set (myclass * p, int x1, int y1) {p–> x = x1; p–> y = y1;}

void main (void)

{

myclass A (5,6);

myclass B (7,8);

cout << A.sum ();

cout << B.sum ();

set (& A, 9,10);

set (& B, 11,12);

cout << A.sum ();

cout << B.sum ();

}

The set function is described in the myclass class as friendly and defined as a normal global function (outside the class, without specifying its name, without the '::' operation and without the friend specifier).

The friendly function does not get the this pointer when called. Class objects must be passed to a friend function only through a parameter.

So, the friendly function:

· Can not be a component function of the class in relation to which is defined as friendly;

· May be a global function;

· May be a component function of another previously defined class.

For example,

class CLASS1
{. . .
int f (...);
. . .
};
class CLASS2
{. . .
friend int CLASS1:: f (...);
. . .
};

// In this example, the class CLASS1 using its component function f ()
// gets access to the CLASS2 class components.

· Can be friendly with respect to several classes;

For example,

// preliminary incomplete class definition

class CL2;
class CL1
{friend void f (CL1, CL2);
. . .
};
class CL2
{friend void f (CL1, CL2);
. . .
};

// In this example, the function f has access to the components of the classes CL1 and CL2.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

C ++ (C plus plus)

Terms: C ++ (C plus plus)