Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Overloading Operator<< works inside the class?

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.

like image 613
howtechstuffworks Avatar asked Feb 19 '12 17:02

howtechstuffworks


2 Answers

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.

like image 147
Anton Golov Avatar answered Sep 22 '22 13:09

Anton Golov


The member function:

ostream &operator<<(ostream &os);

does work, but not for the situation you want. It will be called when you do something like:

A a;
a << std::cout;

i.e. where the object is the left-hand side of the operator.

like image 43
Oliver Charlesworth Avatar answered Sep 22 '22 13:09

Oliver Charlesworth