1.Write a c++ program to find Maximum out of two numbers using friend function. Here one member is of one class and second belongs to another class.
2.Write a c++ program to swap the values of private data members of classes names classOne and classTwo using friend keyword.
program for problem 1
#include <iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
// declaring type
class two;
class one
{
int x;
public:
// using friend function
friend void max(one,two);
}first;
class two
{
int y;
public:
friend void max(one,two);
}second;
void max(one x,two y)
{
// declaring number1 and number2
int number1,number2;
// prompting user
cout << "Enter a positive integer: ";
// taking input
cin >> number1;
// assigning number1 to class one member x
x.x=number1;
cout << "Enter a positive integer: ";
cin >> number2;
// assigning number1 to class two member y
y.y=number2;
cout<<"\nFirst no: "<<x.x;
cout<<"\nSecond no: "<<y.y;
// comparing numbers
if(x.x>y.y)
{
cout<<"\n"<<x.x<<" is maximum";
}
else
{
cout<<"\n"<<y.y<<" is maximum";
}
}
int main()
{
// calling
max(first,second);
getch();
}
OUTPUT SCREEN
program 2 solution
#include <iostream>
using namespace std;
// declaring class one
class one;
// declaring class two
class two
{
public:
void print(one& x);
};
class one
{
int a, b;
friend void two::print(one& x);
public:
one() : a(1), b(2) { }
};
void two::print(one& x)
{
// printing output
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main()
{
// creating objects to one and two classes
one Oneobj;
two Twoobj;
Twoobj.print(Oneobj);
}
Get Answers For Free
Most questions answered within 1 hours.