views:

110

answers:

4

For a school assignment I have to find a solution to the following problem;

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.

#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();
}
+8  A: 

Look into the friend keyword.

Brian R. Bondy
+3  A: 

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
+2  A: 

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
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
@Brian: Yes I agree but this I think is not a valid reason for your downvote.
Prasoon Saurav
@Prasoon Saurav: 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
@Brian: No hard feelings. I just thought only you have commented on my post so the downvote would most probably be yours.
Prasoon Saurav
A: 

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.

DeadMG