Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 258
Thizzer Avatar asked Sep 14 '26 10:09

Thizzer


2 Answers

Look into the friend keyword.

like image 174
Brian R. Bondy Avatar answered Sep 16 '26 22:09

Brian R. Bondy


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.

like image 31
Konrad Rudolph Avatar answered Sep 16 '26 22:09

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!