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();
}
Look into the friend keyword.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With