-1

I want to find the maximum of 2 numbers but instead of the simple method, i need to use 2 classes and friend functions. How to implement it? I am using the following code but the code isn't working.

#include<iostream>
using namespace std;

class one
{
    int a;
    public:
    friend int cal(one a);

};
class two
{
    int b;
    public:
    friend int cal(one a,two b);

};

 cal(int f,int g)
{
    int ans=(x.a>y.b)?x.a:y.b;
}
int main()
{
    one x;
    two y;
    cal(10,20);
}
Shubam Bharti
  • 73
  • 1
  • 2
  • 11
  • Also, will it work if i create the object of the class just after the class ends? – Shubam Bharti Sep 08 '17 at 07:22
  • 1
    Sounds like overkill, but that's probably the way your homework is phrased. Are you sure you want to have two different classes that you want to compare? Or does the assignment mean: use one class to store the numbers and one class that finds the maximum of two of such numbers? – CompuChip Sep 08 '17 at 07:26
  • @CompuChip Yes the assignment says to use 2 classes and friend function. But I couldn't figure out a proper way. – Shubam Bharti Sep 09 '17 at 16:19

2 Answers2

0
#include<iostream>

using namespace std;

class biggest

{

   private:

    int a,b;

    public:

        void input();

            void display();



};

void biggest::input()

{

    cout<<"Enter 2 nos.:";

    cin>>a>>b;

}

void biggest::display()

{

    if(a>b)

    cout<<"Biggest no.:"<<a;

    else

    cout<<"Biggest no.:"<<b;

}

int main()

{

    biggest b;

    b.input();

    b.display();


}

Output

Enter 2 nos.:133 21

Sample Output

Biggest no.:133

CompuChip
  • 9,143
  • 4
  • 24
  • 48
0

By setting a function as a "friend", you give it access to private members of a class. Example looked really strange, but I guess this will do it. Both classes here give private members access to "cal" function.

#include<iostream>
using namespace std;

class one;
class two;

class one
{
    int a = 10;
    public:
    friend int cal(one a,two b);

};
class two
{
    int b = 20;
    public:
    friend int cal(one a,two b);

};

int cal(one x,two y)
{
    return (x.a>y.b)?x.a:y.b;
}

int main()
{
    one x;
    two y;
    cout << cal(x,y);
}
metamorphling
  • 369
  • 3
  • 9
  • Please, note that friend functions don't need public visibility to be accessible, but adding some constructors would make this code more general. – Bob__ Sep 08 '17 at 08:59
  • @Bob__ I didn't make friend function public for a specific reason but just because the other declarations were being made there. – Shubam Bharti Sep 09 '17 at 16:21