//friend function
//***************
/*friend function is declared in the class with friend keyword. it must be defind outside the class to which
it is a friend.friend function is not the member function of the class to which it is a friend.*/
#include<iostream>
using namespace std;
class A; //declare the first class
class B //defining the second class
{
private: //private part of the class
int b;
public: //public part of the class
void getval(int x)
{
b=x;
}
void putval()
{
cout<<"the value of b is:"<<b<<endl;
}
friend void add(A,B); //declare the friend function
};
class A //defining the first class
{
private: //private part of the class
int a;
public: //public part of the class
void getval(int x)
{
a=x;
}
void putval()
{
cout<<"the value of a is:"<<a<<endl;
}
friend void add(A,B); //declare the friend function
};
void add(A ob1,B ob2) //define the friend function outside the class
{
cout<<"the sum is:"<<ob1.a+ob2.b<<endl;
}
int main()
{
A a; // making object of first class
B b; //making object of second class
a.getval(100);
b.getval(200);
a.putval();
b.putval();
add(a,b); //passing object as a function
}
No comments:
Post a Comment