1) Write a C++ Program to swap data members of two objects of a class using friend function.
2)Write a C++ program to demonstrate friend class.
SOLUTION TO THE ABOVE QUESTION
part 1.
1) Write a C++ Program to swap data members of two objects of a class using friend function.
SOLUTION CODE
#include <iostream>
//forward declaration
class myclass_for_object_2;
class myclass_for_object_1
{
public:
int get(){return a;}
private:
int a=456;
friend void swap(myclass_for_object_1 &myclass_for_object_1, myclass_for_object_2 &myclass_for_object_2);
};
class myclass_for_object_2
{
public:
int get(){return a;}
private:
int a=654;
friend void swap(myclass_for_object_1 &myclass_for_object_1, myclass_for_object_2 &myclass_for_object_2);
};
void swap(myclass_for_object_1 &myclass_for_object_1, myclass_for_object_2 &myclass_for_object_2)
{
int a = myclass_for_object_1.a;
myclass_for_object_1.a=myclass_for_object_2.a;
myclass_for_object_2.a=a;
}
int main()
{
myclass_for_object_1 f ;
myclass_for_object_2 s ;
std::cout<<f.get()<<' '<<s.get()<<std::endl;
swap(f,s);
std::cout<<f.get()<<' '<<s.get()<<std::endl;
return 0;
}
SAMPLE PROGRAM OUTPUT
part 2
2)Write a C++ program to demonstrate friend class.
SOLUTION CODE
#include <iostream>
class my_class {
private:
int variable_1;
public:
my_class() { variable_1 = 20; }
friend class friend_to_my_cclass; // Friend Class
};
class friend_to_my_cclass {
private:
int variable_2;
public:
void show_method(my_class& value)
{
// Since friend_to_my_cclass is friend of my_class, it can access
// private members of my_class
std::cout << "My_class::variable_1=" << value.variable_1;
}
};
int main()
{
my_class variable_1;
friend_to_my_cclass variable_2;
variable_2.show_method(variable_1);
return 0;
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment