c++functionclassfriendborland-c++

How to pass objects as arguments?


I have changed the code here all the variables have to remain private and using friend functions is a requirement. Here there are two classes A and B and I am supposed to accept 5 numbers(void enter()).The function average is to be able to access all variables and give the average. I know that currently the line

 obj2.average(a,b,c,d,e);

will give an error as the variables are not accessible so my question is, how do I pass the variables in the last line?

#include<iostream.h>
#include<conio.h>

class A
{
 int a;
 int b;

 public:
 friend class B;
 int enter1()
 {
  cout<<"enter the value of a and b"<<endl;
  cin>>a>>b;
  return(a,b);
 }
};

class B
{
 int c;
 int d;
 int e;

 public:
 void average(int a, int b, int c, int d, int e)
 {
 float avg;
 avg=((a+b+c+d+e)/5);
 cout<<"average is "<<avg<<endl;
 }

 int enter()
 {
 cout<<"enter the value of c,d,e"<<endl;
 cin>>c>>d>>e;
 return(c,d,e);
 }
 };

void main()
{
 A obj1;
 B obj2;
 obj1.enter1();
 obj2.enter();
 obj2.average(obj1.a,obj1.b,obj2.c,obj2.d,obj2.e);
}

Solution

  • You can not access member variables in the main function because they are private. You can send the first instance to the method as a parameter, then use the class A member variables inside the method.

    #include<iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    
    class A
    {
     int a;
     int b;
    
     public:
     friend class B;
     int enter1()
     {
      cout<<"enter the value of a and b"<<endl;
      cin>>a>>b;
      return(a,b);
     }
    };
    
    class B
    {
     int c;
     int d;
     int e;
    
     public:
     void average(A obj)
     {
     float avg;
     avg=((obj.a+obj.b+c+d+e)/5);
     cout<<"average is "<<avg<<endl;
     }
    
     int enter()
     {
     cout<<"enter the value of c,d,e"<<endl;
     cin>>c>>d>>e;
     return(c,d,e);
     }
     };
    
    int main()
    {
     A obj1;
     B obj2;
     
     obj1.enter1();
     obj2.enter();
    obj2.average(obj1);
    return 0;
    }