views:

161

answers:

5

Hi all.

Let's say I make a class, like, which contains a char array. Now, what operator handles this:

myClass inst;
cout << inst;

At the "cout << inst;" what is called, by simply the class' name? Thanks.

+11  A: 

What is called is std::ostream &operator<<(std::ostream &, myClass const &). You can overload this if you want.

larsmans
+2  A: 

The compiler will look for an overload of operator<<. In particular, it will look for either a member-function overload of std::ostream (won't exist), or a free function, that you should overload with the following prototype:

std::ostream &operator<< (std::ostream &os, const myClass &x);

You may need to make this a friend of myClass if you need to access protected/private members.

Oli Charlesworth
+2  A: 

This results in compiler error, unless you have an overloaded typecast operator for some type that ostream knows. You can add your own types to the types that ostream knows by overloading the global ostream& operator(ostream& os, const myClass& x) or making your type convertible to a string/int etc. Be careful though, the typecast overloading can shoot you in the foot and is considered a bad practice.

The simplest way is just printing some variables from your class:

myClass inst;
cout << inst.getName() << ": " << inst.getSomeValue();
dark_charlie
+1  A: 

To be able to use std::cout << someClass, you have to create an operator like following :

std::ostream &operator<< (std::ostream &, const someClass &);
Xavier V.
+3  A: 

By creating a friend output operator, as in the following example.

#include <iostream>

class MyClass {
  friend std::ostream & operator<<(std::ostream &out, const MyClass &inst);
public:
  // ... public interface ...
private:
  char array[SOME_FIXED_SIZE];
};

std::ostream & operator<<(std::ostream &out, const MyClass &inst)
{
   out.write(inst.array, SOME_FIXED_SIZE);
   return out;
}

Please not this makes some assumptions about what you mean by "char array", it is greatly simplified if your char array is actually nul (0 character) terminated.

Update: I will say this is not strictly a return value for the class, but rather a textual representation of the class -- which you are free to define.

Marc
Doesn't have to be friend function, but then you have to add another public function method to the class, which will really print values (or whatever) to the ostream.
VJo
It may be that all the information needed to print the object is available in public functions. The `operator<<()` has to be external to the class (since the first argument isn't of the class type). It can be a `friend`, if it gets all its information from the public class interface. It can call a member function to perform the printing, and sometimes this is a good idea.
David Thornley
@VJo + @David -- yes I totally agree it does not need to be a friend function if you can collect all the information from the public interface.
Marc