C++ program to access private members of two classes by outer non-member function i.e. FRIEND FUNCTION

//class ABC with 'p' as private data member
//class XYZ with 'q' as private data member
//define independent i.e. non-member function to calculate mean value of 'p' and 'q'

#include <iostream>
using namespace std;
class XYZ;
class ABC
{
    int p;
    public:
        void readABC()
        {
            cout<<"Enter p: ";
            cin>>p;
        }
    friend float average(ABC,XYZ);
};
class XYZ
{
    int q;
    public:
        void readXYZ()
        {
            cout<<"Enter q: ";
            cin>>q;
        }
    friend float average(ABC,XYZ);
};
float average(ABC a, XYZ x)
{
    return (a.p+x.q)/2.0;
}
int main()
{
    ABC a;
    XYZ x;
    a.readABC();
    x.readXYZ();
    float avg=average(a,x);
    cout<<"Average = "<<avg;
    return 0;
}

No comments:

Post a Comment