Home > Net >  How to access variable of private class?
How to access variable of private class?

Time:01-07

In the given lines we can have one or more lines of code. I tried my logic but since all variables are private of class Student I can't access them using object of Average Calculator class.

We can fill in these 3 lines or leave if not required

Question_Link!

#include <iostream> 
#include <iomanip>
using namespace std; 
____________________
class Student
{ 
    int maths; int physics; int chemistry; 
    ____________________
};  
class AverageCalculator
{ 
    Student stud; 
    public: 
        void setStudentMarks(int maths, int physics, int chemistry)         { 
            stud.maths = maths; 
            stud.physics = physics; 
            stud.chemistry = chemistry; 
        }
        double getAverageMarks()
        { 
            return ____________________; 
        }
}; 
int main() {
int maths, physics, chemistry; 
cin >> maths >> physics >> chemistry; 
AverageCalculator avgCalc; 
avgCalc.setStudentMarks(maths, physics, chemistry);
cout << fixed << setprecision(2) << avgCalc.getAverageMarks(); return 0; 
    
} 

Example:
Input:
45 15 40
Output:
33.33

CodePudding user response:

I can't resist posting an answer to what is a reasonably amusing quiz.

The first area (just below using namespace std; - naughty by the way) can be left blank.

In the second area, write

friend class AverageCalculator; // pure evil - symptomatic of poor class design.
double getAverageMarks() const
{
    return (maths   physics   chemistry) / 3.0; // obviate integer division
}

and in the third block, write

return stud.getAverageMarks();

There's much room for improvement in this design though. Provide a public constructor for Student. Then you can drop the friendship.

There's no real need for the auxiliary AverageCalculator class.

  •  Tags:  
  • Related