C++ | Friend Function

Introduction

This is a tutorial on how to use friend function in c++. The program is given below that adds two numbers using friend function. The program is extendable. Go enjoy the program. Lets begin…….

Program for friend function

#include<iostream.h>
#include<conio.h>
//declare two classes.
class two;
class one
{
int a;
public:
void geta(void)
{
cout<<“Enter number:”;
cin>>a;
}
one sum(two t);
void print(void)
{
cout<<“Sum = “<<a;
}
};
class two
{
int a;
public:
void geta(void)
{
cout<<“Enter number:”;
cin>>a;
}
friend one one::sum(two);
};
//function of one
one one::sum(two t)
{
one tmp;
tmp.a=a+t.a;
return (tmp);
}
//main function
void main()
{
//clear the screen.
clrscr();
//declare x,z as one and y as two.
one x,z;
two y;
//Call functions
x.geta();
y.geta();
z=x.sum(y);
z.print();
//get character
getch();
}

Output

Enter number:1
Enter number:3
Sum = 4

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of c++ which can be used in any program….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Declare two classes.
  3. Declare friend function.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Declare the x,y,z as your class name.
  7. Call the functions.

At the end

You learnt creating the C++ program for friend function in c++. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s