I recently needed to add member functions like these into my class

istream& read(istream&) ;
ostream& print(ostream&);

I am a little confused on how to actually call these functions within my class. I am more familiar with overloading the insertion and extraction operator since the prototype for those makes a lot more sense to me; however, one of my program spec is that I need to use these. What do I need to put into the function as a parameter?

Edited by red999: n/a

8 Years
Discussion Span
Last Post by red999

Typically you pass in any object derived from istream or ostream (such as cin, cout, any fstream object, any stringstream object, etc...). Equally typically, the return value is used to get the result of the operation:

if (!foo.read(std::cin))


Will using

cout << foo.print;
cin >> foo.read;

works too? My book talks about user-defined output stream manipulators and that is how the example called the function. I thought the example was a little weird since the functions were not called like the usual way.

Edited by red999: n/a


No, that won't work. To use the zero-argument manipulator syntax, the manipulator has to be either a static member function, or a non-member function. non-static member functions aren't compatible with the type expected for a manipulator function, so if your book is using that as an example, it's wrong.

However, a static member function can be called through an object instance, so if your book is declaring read and print as static, then that's okay:

#include <iostream>
#include <ostream>

class foo {
  static std::ostream& print_static(std::ostream& out)
    return out<<"foo!";

  std::ostream& print_instance(std::ostream& out)
    return out<<"foo!";

std::ostream& print_global(std::ostream& out)
  return out<<"not foo!";

int main()
  std::cout<< print_global <<'\n'; // Okay

  foo f;

  std::cout<< foo::print_static <<'\n'; // Okay
  std::cout<< f.print_static <<'\n'; // Okay
  std::cout<< f.print_instance <<'\n'; // Error

Edited by Narue: n/a


That definitely was helpful. Thanks. I forgot to mention that the example that my book gave was of non-member function stream manipulator (everything was inside main.cpp) so I thought that it implied that it works the same way for member functions.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.