Friend function C++ program

Description


This program demonstrates friend function in c++. A friend function is a non member function of a class, which can access all the private and protected members of the class. A friend function is preceded by the keyword friend. The program implements a friend function add(), which is defined outside the class second, but still access the private variables a, b and c.

Program


//Friend function c++

#include<iostream.h>

#include<conio.h>

class second

{

int a,b,c;

public:

void getdata(int p,int q)

{

a=p;b=q;

}

friend int add(second s);

};

int add(second s)

{

s.c=s.a+s.b;

return s.c;

}

void main()

{

int d;

second s;

s.getdata(10,5);

d=add(s);

cout<<"Sum= "<<d;

getch();

}


No comments: