How do C++ streams work?

c++, class, iostream, oop

Solution

Let's create a class that looks like `cout` (but without as many bells and whistles).

#include <string>

class os_t {
    public:
        os_t & operator<<(std::string const & s) {
            printf("%s", s.c_str());
            return *this;
        }
};

int main() {
    os_t os;

    os << "hello\n";
    os << "chaining " << "works too." << "\n";
}

Notes:

- `operator<<` is an operator overload just like `operator+` or all of the other operators.

- Chaining works because we return ourselves: `return *this;`.

What if you can't change the `os_t` class because someone else wrote it?

We don't have to use member functions to define this functionality. We can also use free functions. Let's show that as well:

#include <string>

class os_t {
    public:
        os_t & operator<<(std::string const & s) {
            printf("%s", s.c_str());
            return *this;
        }
};

os_t & operator<<(os_t & os, int x) {
    printf("%d", x);
    return os;

    // We could also have used the class's functionality to do this:
    // os << std::to_string(x);
    // return os;
}

int main() {
    os_t os;

    os << "now we can also print integers: " << 3 << "\n";
}

Where else is operator overloading useful?

A great example of how this kind of logic is useful can be found in the GMP library. This library is designed to allow arbitrarily large integers. We do this, by using a custom class. Here's an example of it's use. Note that operator overloading let's us write code that looks almost identical to if we were using the traditional `int` type.

#include <iostream>
#include <gmpxx.h>

int main() {
    mpz_class x("7612058254738945");
    mpz_class y("9263591128439081");

    x = x + y * y;
    y = x << 2;

    std::cout << x + y << std::endl;
}

Problem

I'd like to know how do stream classes work in C++. When you say: ``` cout<<"Hello\n"; ``` What does exactly do "<<". I know that cout is an object form iostream that represents the standard output stream oriented to narrow characters (char). In C "<<" is the bitwise shift operator so it moves bits to the left but in C++ it's and insertion operator. Well, that's all I know, I don't really understand how does this work under the hood. What I'm asking for is detailed explanation about stream classes in C++, how they are defined and implemented. Thank you very much for your time and sorry for my English.

Original source

Related problems