Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading