Search code examples
c++scopeglobal-scope

Access private variable in global scope


In this below code, the foo function in the global scope tries to access the private variables of a Box, which ofcourse doesn't work. I have to make the foo function work with one line of code at the place show code for a school assignment.

#include <iostream>

using namespace std;
class Box {
      int x,y;

      public:
             Box(int xi,int yi) {x=xi;y=yi;}
             // One line of code to make foo(Box, Box) work
};

bool foo(Box l,Box r) {return (l.x*l.y)>(r.x*r.y);}

int main(int argc, char* argv[]) {
    Box b1(3,4),b2(1,2);

    if (foo(b1,b2)) cout << "b1>b2\n";

    return cin.get();
}

Solution

  • Declare foo as a friend function inside Box

       #include<iostream>
    
       class Box {
         int x,y;
    
         public:
             Box(int xi,int yi) :x(xi),y(yi){}// Always use initializer list for initializing data members, i.e. prefer initialization over assignment
    
             friend bool foo(Box,Box);// friend functions can access private members
       };
    
       bool foo(Box l,Box r)       // friend keyword not to be written while defining the function
       {return (l.x*l.y)>(r.x*r.y);}
    
       int main(int argc, char* argv[]) {
          Box b1(3,4),b2(1,2);
    
          if (foo(b1,b2)) std::cout << "b1>b2\n";
    
         return std::cin.get();
       }