Is it bad to make a reference parameter optional by giving it a default value? Like here:

int Parse(std::string filename, std::string& error = (std::string)"");

Here, the caller of the function may pass an optional std::string that will be filled with an error message if there is one. Is this considered "ok", both as far as being safe, good code and having good style?

Recommended Answers

All 2 Replies

It's legal construct (better use more accurate std::string(""), avoid old C style casts).

I don't like this style (tastes differ). It's an ineffective code (string constructor works on every call for default argument). It's some confusing code (pass by reference means inout parameter as ususlly).

In that case I prefer const char* msg = 0 - programmer's intentions are more evident...

There is nothing wrong with it. You'll just get a reference to a temporary default.

The best advice is to write const std::string& error = std::string() as your argument. This will take strings and char*s equally.

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.