2

I tried overloading the << operator as shown directly into the public section of a class but it didn't work

ostream& operator<< (ostream& output, const Box& B){
        output << B.l << " " << B.b << " " << B.h;
        return output;
}

I tried overloading the << operator as shown above directly into the public section of a class but it didnt work, after asking a senior programmer about this he wrote this outside the class & made it a friend function:

friend ostream& operator<< (ostream& output, const Box& B){
        output << B.l << " " << B.b << " " << B.h;
        return output;
}

1 Answers1

2

In this pseudo-example

class Thing
{
  ...
  void work(int arg);
  ...
};

the member-function is a kind of function implicitly taking a Thing as first argument, like if my_thing.work(12) was work(my_thing, 12). It is absolutely not a valid substitution, but it is just to give the idea for the remaining of the explanation.

Back to your example, when you write std::cout << my_box, the compiler understands the usage of the operator << as this function call operator<<(std::cout, my_box). If operator<< for Box was a member-function of std::cout this could work, but actually the standard streams don't know anything about your Box type.

If you provide operator<< as a member-function of Box, then it means that the left operand, which could be considered as a hidden first parameter as described in the pseudo-example above, should be a Box. But when you write std::cout << my_box, the left operand is not a Box but std::cout.

In this case, the only solution is to provide a non-member function with the expected arguments in the correct order, hence the second solution you tried and found as working.

prog-fh
  • 13,492
  • 1
  • 15
  • 30