Is it possible to use ostream/ofstream class as a function parameter

As ostream and ofstream are classes, I am curious if they can be a function parameter.

Here's the code I have tried.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

void test(std::ostream output)
{
	output << "testing...\n";
}

int main()
{
	test(std::cout);
	return 0;
}


I tried to compile it and it gives me this.
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member

Is there anyway I can get around it?
Yes... but some streams (like cout) are not copyable... so you generally don't pass them by value. You pass them by reference:

1
2
3
4
void test(std::ostream& output) // <- note the & ... that means we pass by ref
{
	output << "testing...\n";
}
Thanks a lot!
Topic archived. No new replies allowed.