Search code examples
c++ostream

Is ostream& operator<< better practice in a class than using std::cout?


In a Linked List class, I created a display method to print out the Linked List as it is currently formulated like so:

void LinkedList::display() {
   Node* curr = m_head;

   while (curr) {
      std::cout << curr->n_data << " -> ";
      curr = curr->n_next;
   }
   std::cout << std::endl;
}

One of the TA's who graded the assignment left a comment:

Never do cout in a class file. Use ostream& operator<< instead.

Classes shouldn't care about where you are outputting to (file/console/etc).

We hadn't yet learned about operator overloading at the time of this assignment, but I'm still not really sure.

How would I actually implement and use the ostream& operator>> to print to the console? Why is this best practice?


Solution

  • The simplest solution in this case would be to add a std::ostream parameter to your display() method, eg:

    void LinkedList::display(std::ostream &out) const {
       Node* curr = m_head;
    
       while (curr) {
          out << curr->n_data << " -> ";
          curr = curr->n_next;
       }
       out << std::endl;
    }
    
    LinkedList list;
    ...
    list.display(std::cout);
    

    Then, if down the line, you decide to overload operator<<, it can simply call display(), eg:

    std::ostream& operator<<(std::ostream &out, const LinkedList &list) {
        list.display(out);
        return out;
    }
    
    LinkedList list;
    ...
    std::cout << list;