Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about the ostream operator <<

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.

like image 643
johnny-john Avatar asked Oct 27 '10 18:10

johnny-john


2 Answers

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

like image 145
Fred Foo Avatar answered Sep 21 '22 06:09

Fred Foo


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.

like image 22
Marc Butler Avatar answered Sep 21 '22 06:09

Marc Butler