Use of friend function is to access the private data member by non member function.
A simple program
#include<iostream>
using namespace std;
class test
{
private:
int a=4;
public:
friend void display(test abc)
{
cout<<"Value of a="<<abc.a;
}
};
int main()
{
test obj;
display obj;
return 0;
}
Output:
Value of a=4;
………………………………………………
………………………………………………
This is the program of the adding of real and imaginary parts of a complex number by using friend function.
#include<iostream>
using namespace std;
class complex
{
private:
int real,imaginary;
public:
void realno()
{
cout<<"Enter real part:";
cin>>real;
}
void imaginaryno()
{
cout<<"Enter imaginary part:";
cin>>imaginary;
}
friend void sum(complex a,complex b)
{
cout<<"Complex no. is: ";
cout<<a.real;
if(b.imaginary<0)
{
cout<<"-i"<<(-1)*b.imaginary;
}
else
{
cout<<"+i"<<b.imaginary;
}
};
int main()
{
complex a,b;
a.realno();
b.imaginaryno();
sum(a,b);
return 0;
}
Output:
Enter real part:3
Enter imaginary part:4
Complex no. is: 3+i4
…………………………………………………
…………………………………………………
A program to join two strings using friend function.
#include<iostream>
#include<string.h>
using namespace std;
class str2;
class str1
{
private:
char a[100];
public:
void getdata()
{
cout<<"Enter a string:";
cin>>a;
}
friend void join(str1,str2);
};
class str2
{
private:
char b[100];
public:
void getdata()
{
cout<<"Enter second string:";
cin>>b;
}
friend void join(str1,str2);
};
void join(str1 aaa,str2 bbb)
{
string c;
c=strcat(aaa.a,bbb.b);
cout<<c;
}
int main()
{
str1 aa;
str2 bb;
aa.getdata();
bb.getdata();
join(aa,bb);
return 0;
}
Output:
Enter a string:Te
Enter second string:st
Test
…………………………………………………
…………………………………………………
FRIEND CLASS
#include<iostream>
using namespace std;
class student1
{
friend class student2;
private:
int marks1=80;
};
class student2:public student1
{
private:
int marks2=70;
public:
void display()
{
cout<<"marks1="<<marks1<<"\nmarks2="<<marks2;
}
};
int main()
{
student2 obj2;
obj2.display();
return 0;
}
Output:
marks1=80
marks2=70
………………………………………………
………………………………………………
CLICK FOR SEARCH TOPIC
No comments:
Post a Comment