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?

Recommended Answers

All 4 Replies

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))
  panic();

foo.print(std::cout);

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.

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 {
public:
  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
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.