C++/query on c++
Expert: Prince M. Premnath - 1/8/2007
Questionhow to sort elements from 2 different classes using friend function
AnswerDear amit !
Lets assume sorting of array in two independent classes using a friend function .
Lets get some ideas about the friend function!
1. Even then a friend function is declared inside a class , its not in the scope of the class where its actually declared.
2. It can be invoked in main function just like an ordinary function ( without using any .operator )
3. Just like a member function , a friend function cannot access the data members of that class where its actually declared , in turn it should use the object of that class !
with this 3 ideas lets implement the problem of sorting elements in two different classes.
Here i give the essential part of the code where the concept of friend function is actually implemented !
#include<iostream.h>
class two; // forward declaration of the class 'two'
class one
{
private :
int array1[10];
public:
// declaration of friend fn
friend void sort(one , two);
// Other member functions
};
class two
{
private:
int array2[10];
public:
friend void sort(one , two);
//other member functions
};
// definition of friend function
void sort( one a , two b)
{
// your code to sort the array elements ;
// using the objects of each class you can access the array
// of both the classes
}
void main()
{
one obj1; // object declaration
two obj2;
// you can invoke the friend function like this
sort( obj1 , obj2);
//rest of the program
}
Note : Since this friend function act as a bridge between the two classes therefore it should be declared in both of the classes.
1. Using any sorting technique you can sort the array in both of the classes .
Regards !
Prince M. Premnath.