Ez2M
Ez2M

Reputation: 51

What's the use of "ostream &os"?

I just started learning C++, and I saw some function in C++ primer like that:

double total_receipt(ostream &os)const{...}

then I try to find the address of cout by using this code: "cout << &cout << endl;"

and that's no difference between ostream &os and direct use cout.

So why not just use cout instead of ostream &os? Or maybe it's just a "good" habit?

Upvotes: 4

Views: 4233

Answers (1)

DWilches
DWilches

Reputation: 23015

First notice:

When you declare a method, you need to use the class names for the parameters, so if your class uses an "output stream" (that's what ostream means) then you declare your function like:

double total_receipt(ostream &os)

You can't create the function like this:

double total_receipt(cout) // doesn't work

Now, if your question is about what is the difference between declaring the total_receipt function like this:

double total_receipt(ostream &os) {
    os << "hello world" << std::endl;
}

or like this:

double total_receipt() {
    std::cout << "hello world" << std::endl;
}

That's up to you. Usually, we use the first one as that allows to invoke the function with other things besides cout, like:

ofstream out_file("my_file.txt");
total_receipt(out_file);

So, you can pass to that function any object of classes derived from ostream, like ofstream in the example. This means, your function can print to a file, besides printing to the terminal, so you add more functionality if you need it.

Upvotes: 5

Related Questions