Does Overloading Operator<< works inside the class?

howtechstuffworks picture howtechstuffworks · Feb 19, 2012 · Viewed 14.8k times · Source

I mean, I was trying to overload the operator<< inside the class

like this

 class A {
      public:
           ostream &operator<<(ostream &os);// which doesnt work

      private:
           friend ostream &operator<<(ostream &os, const A& a); //Works
           int i;

 };

  Definition
          ostream &operator<<(ostream &os, const A& a) {
              os<<a.i;
              return os;
          }

why can't I overload the operator inside the class specific to class? or Am I missing something? or Am I stupid to even think in such a way? Please advise.

Answer

Anton Golov picture Anton Golov · Feb 19, 2012

The problem is that your operator<< would take ostream as a second parameter, not a first one. That way, you could do myObject << std::cout, but it would look unintuitive and you would not be able to chain calls due to operator<< being left-associative.

Another benefit of declaring the operator as a friend as opposed to a member function is that automatic conversions can occur. That means that if you have a class B that doesn't derive from A but does have a B(A const&) constructor, you will still be able to do std::cout << my_b; and have it converted to an A and then printed.

Fortunately, defining operator<< as a friend can be done within the class if you prefer to. Your code could be written as

class A {
    int i;
    friend std::ostream& operator<<(std::ostream& o, A const& a) {
        o << a.i;
        return o;
    }
};

Why doesn't the standard allow for you to specify which side the argument should go on? Let's pretend it did, and add the left_of and right_of keywords to specify:

struct B;

struct A {
     A left_of operator+(B const&) {
         return *this;
     }
};

struct B {
     B right_of operator+(A const&) {
         return *this;
     }
};

What happens now when we do A a; B b; f(a + b);? Each class has an operator that handles this case, which means we can't decide. Seeing as many operators should be friends due to the conversion possibilities anyway, not allowing this kind of thing is not that big a problem, and prevents these kind of ambiguities. (Of course, you could also define a member operator and a free one, which would cause a very similar problem.)

By the way, as things are, the definition of your friend operator<< isn't returning anything, which will mess up chaining.