-3

I know std::cin >> x will store vales from the input stream in the variable x. I also know that cin will scan the input stream as long as possible to get a valid representation of x (skipping any white space). However, how is this behavior defined for different data types, and what data types are supported?

Does cin simply have a different overload on >> for each type? Does it only support fundamental data types?

Similarly, how does std::cout know how to print out a value? I'm assuming it uses an implicit conversion to a string, but I couldn't confirm that.

Peter Moran
  • 295
  • 3
  • 13
  • 1
    You are asking several questions. The 3rd part is a duplicate of https://stackoverflow.com/questions/2981836/how-can-i-use-cout-myclass – François Andrieux Oct 31 '17 at 14:35
  • Thanks. I was assuming they were related, and that answering one would help with the others. – Peter Moran Oct 31 '17 at 14:36
  • 2
    `operator>>` for input and `operator<<` for output are overloaded for each type. It doesn't only support fundamental types, e.g. std::string isn't fundamental, and you can overload it yourself to support your own classes. `cout` doesn't know how to print out a value, the relevant overload for the type you're passing does though. – Steve Oct 31 '17 at 14:44

1 Answers1

1

The compiler collects a set of functions named operator<< (or operator>>) from a variety of places:

  • current scope
  • members of the left-hand operand and its base classes
  • namespace of the left-hand operand (which may be defined inside the class using the friend keyword)
  • namespace of the right-hand operand (which may be defined inside the class using the friend keyword)
  • built-in versions that apply to primitive integral types

It then performs overload resolution in the same way as when calling a function with an "ordinary" name in order to determine which of these to use. Implicit conversions are considered during overload resolution, but generally providing iostream support for a data type includes providing a match that is more direct than an implicit conversion to string would be (for example, reference conversions are better).

Since the left-hand operand here is std::cout (or std::cin), you don't have much control over its members or its namespace. And you cannot change the built-in versions. But that still gives you several ways to add support for new types -- as the program author, use the current scope, and as a library author, use the namespace of the class you write.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Thank you. With this clarification, I was able to research further. I found this post to be quite helpful: [Overloading stream insertion (<>) operators in C++](http://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/) – Peter Moran Oct 31 '17 at 15:40