I was recently watching a couple videos on C++. Within the video the person said that usually you don’t want to use input/output within a class. Can someone please elaborate why? Is it just what this guy is saying or is it some kind of standard within programming? Instead he was using
Throw
instead of cout/print/printf.
Basically video said you shouldn’t be using input/output within classes. Is this an industry standard? If so why?
Classes that are designed for reusability shouldn't make too many assumptions about where they will be used. Imagine you create a C++ class to encapsulate the idea of a file, such as:
class CFile {
public:
CFile(const char* path);
void rename(const char* new_path);
std::vector<char> get_content();
};
This class is highly reusable. Today, it may be used in a console application, where it may be OK to write information to stdout. Tomorrow, it may be used in a GUI application, where it doesn't make any sense to write to stdout. It probably makes more sense for the rename()
method to throw an exception on error than to write to stdout. The client application (console vs. GUI) can then choose to handle the error however they choose.
In practice, however, you'll find that most systems are a mix of reusable classes (classes which can be easily pulled out of one application and used as-is in another application) and focused classes (classes that are designed to handle a use case that is specific for the program). It may be preferable for a focused class to assume its use case, in which case it should feel free to write to stdout. For example, your main()
method may simply be something like the following:
int main(int argc, char* argv[]) {
CMyApplication application;
return application.run(argc, argv);
}
In this case, all of your application's functionality is likely in classes, and the "controller" or "driver" for all of your application is the class CMyApplication
. This class can write to stdout all it wants, if it's appropriate to do so.