Friend functions in C++:

In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends. Friends are functions or classes declared as such. If we want to declare an external function as the friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class and preceding it with the keyword friend. Properties of friend function:
1. It is not within the scope of the class to which it has been declared as the friend.
2. Since it is not within the scope of the class, it cannot be called using the object of that class
3. It can be invoked like a normal function w/o the help of an object.
4. It can be declared in private or in the public part of the class.
5. Unlike member functions, it cannot access the member names directly and has to use an object name and dot operator with each member name.

// friend functions 
Program Code:
#include <iostream> 
using namespace std; 
class CRectangle 
int width, height; 
public: 
void set_values (int, int); 
int area () 
{
return (width * height);
friend CRectangle duplicate (CRectangle); 
}; 
void CRectangle::set_values (int a, int b) 
width = a;
height = b; 
CRectangle duplicate (CRectangle rectparam) 
CRectangle rectres; 
rectres.width = rectparam.width*2; 
rectres.height = rectparam.height*2; 
return (rectres); 
int main () 
CRectangle rect, rectb; 
rect.set_values (2,3); 
rectb = duplicate (rect); 
cout << rectb.area(); 
return 0; 
}

The duplicate function is a friend of CRectangle. From within that function, we have been able to access the member's width and height of different objects of type CRectangle, which are private members. Notice that neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate a member of class CRectangle.

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: