2

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();
}
Ren
  • 1,111
  • 5
  • 15
  • 24
Thizzer
  • 16,153
  • 28
  • 98
  • 139

4 Answers4

9

Look into the friend keyword.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
3

First off, this is not a priori a dirty thing. The placement of the comment line already indicates that the class Box controls who is allowed to touch its privates (pun intended).

Secondly, since this is a school assignment I think that the solution should have been mentioned in class: this can be achieved using a friend declaration.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

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();
   }
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 3
    For questions tagged homework I think it's better to give the needed guidance without the exact code. That way they can look into what you tell them and learn from it instead of copy/pasting. – Brian R. Bondy Jun 21 '10 at 13:48
  • @Brian: Yes I agree but this I think is not a valid reason for your downvote. – Prasoon Saurav Jun 21 '10 at 15:32
  • You're making an assumption, I didn't downvote. Check my account number of downvotes. I rarely downvote. I like to leave comments instead. Probably one of the people that pressed up on my comment. – Brian R. Bondy Jun 21 '10 at 15:34
  • @Brian: No hard feelings. I just thought only you have commented on my post so the downvote would most probably be yours. – Prasoon Saurav Jun 21 '10 at 15:51
0

In addition to the other answers involving friends, a better answer for the long term (although not a one-line change) would be for Box to overload the appropriate comparison operators.

Puppy
  • 144,682
  • 38
  • 256
  • 465