Program in c++ to use 2 classes and find maximum of 2 numbers

13.8k views Asked by At

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);
}
2

There are 2 answers

0
Tukihost Nepal On BEST ANSWER
#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

2
metamorphling On

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);
}