tags:

views:

318

answers:

3

Hey Stackoverflow,

I found this function in the header file of an abstract class:

virtual ostream & print( ostream & out ) const;

Can anyone tell me what kind of function this is and how to declare it in a derived class? From what I can tell, it looks like it returns a reference to an outstream.

If I implement it in my cc file with nothing in it, I get a compiler error:

error: expected constructor, destructor, or type conversion before ‘&’ token

Can someone show me a simple implementation of how to use it?

+1  A: 
#include <iostream>
using namespace std;

struct A {
  virtual ostream & print( ostream & out ) const {
      return out << "A";
  }
};

It is common to make a print function virtual, because the << operator commonly used for stream output cannot be made so (because it is not a member function).

anon
A: 

some implementation:

ostream& ClassA::print( ostream& out) const
{
    out << myMember1 << myMember2;
    return out;
}

Returning the same ostream allows combinations like

a.print( myStream) << someOtherVariables;

However, it is still strange to use it this way.

Regarding the error, ostream is part of std namespace, and not part of the global namespace or the namespace the class you're refering is part of.

Cătălin Pitiș
+1  A: 

You probably forgot to include iostream which makes ostream visible. You also need to change this into std::ostream, because C++ standard library names are within the namespace std.

Do not write using namespace std; in a header-file, ever!

It's ok to place it into the implementation file, if you want, or if you write up an example for a friend. Because any file that includes that header will have all of the standard library visible as global names, which is a huge mess and smells a lot. It suddenly increases the chance for name-clashes with other global names or other using'ed names - i would avoid using directives at all (see Using me by Herb Sutter). So change the code into this one

#include <iostream>
// let ScaryDream be the interface
class HereBeDragons : public ScaryDream {
    ...
    // mentioning virtual in the derived class again is not
    // strictly necessary, but is a good thing to do (documentary)
    virtual std::ostream & print( std::ostream & out ) const;
    ...
};

And in the implementation file (".cpp")

#include "HereBeDragons.h"

// if you want, you could add "using namespace std;" here
std::ostream & HereBeDragons::print( std::ostream & out ) const {
    return out << "flying animals" << std::endl;
}
Johannes Schaub - litb
+1 for the descriptive class names :)
Eric