You are here:

C++/query on c++


how to sort elements from 2 different classes using friend function

Dear 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 !


class two; // forward declaration of the class 'two'

class one
  private :
     int array1[10];
     // declaration of friend fn
     friend void sort(one , two);
  // Other member functions          

class two
     int array2[10];
     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.


All Answers

Answers by Expert:

Ask Experts


Prince M. Premnath


Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)


More than 5 years


©2017 All rights reserved.