Search code examples
c++standards

Is std::cout in a header file bad practice?


This might be a duplicate question but all of my search results talk about not putting using into a header file, which is not my question. I have read up on this and understand why you should not place using inside of a header file.

I am new to C++ and am trying to make sure I am learning/using best practices. I know header files are meant for defining classes, structs and the like and should never "do" anything. Does this include std::cout? Is that considered doing something? What I mean is, is it okay to print output from a header file, or should i return data to my *.cpp file and do the output from there? Or does this not really matter?


Solution

  • IMHO ...

    Use of std::cout in any file in a library is a symptom of poor design. If you need to output something, provide the interface for the client code to pass a ostream or an ostream-like object that supports inserting data to it.

    Use of std::cout in an application-specific file, be it a header file or a .cpp file, is perfectly fine.