BeLioN
BeLioN

Reputation: 11

Instantiating class in member call

I have a member function defined as:

void printSomeData(std::ostream& str) const;

When I try to call that member from another class this way:

myclass.printSomeData(std::ofstream("foo.txt"));

I get the following errors:

error: no matching function for call to ‘myclass::printSomeData(std::ofstream)’

note: no known conversion for argument 1 from ‘std::ofstream {aka std::basic_ofstream}’ to ‘std::ostream& {aka std::basic_ostream&}’

However, if I call the function first instantiating the ofstream like below, I do not get any error, which I do not really understand:

std::ofstream foo("foo.txt");
myclass.printSomeData(foo);

Anyone can give me a clue?

Thank you

Upvotes: 1

Views: 100

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

You cannot bind a temporary to a non-const reference, which you are doing here:

myclass.printSomeData(std::ofstream("foo.txt"));
                            ^ temporary std::ostream object

When can do this instead:

std::ofstream os("foo.txt");
myclass.printSomeData(os);

you are passing a reference to an existing std::ofstream object, not a temporary.

You could also make printSomeData take a const reference, but presumably you want to change the stream in your function.

Upvotes: 3

ForEveR
ForEveR

Reputation: 55887

void printSomeData(std::ostream& str) const;

myclass.printSomeData(std::ofstream("foo.txt"));

You try pass to function that take reference temporary-object (i.e. try to bind rvalue to lvalue-reference). It's incorrect. You can use const std::ostream&, but it's not good, also you can use std::ostream&& if you can use C++11.

void printSomeData(std::ostream&& str) const;
myclass.printSomeData(std::ofstream("foo.txt"));

But you cannot pass object of type ostream in this case.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

void printSomeData(const std::ostream& str) const;
//                   |
//              notice const

Temporaries can't bind to non-const references, and std::ofstream("foo.txt") creates a temporary.

Or you can provide a non-temp to the function.

Upvotes: 1

Related Questions