I have a C++ class in which I have a constructer that takes char*,char*, ostream
. I want to provide a default value for the ostream
(cerr
). Is this done in the header or the .cpp
file?

- 34,849
- 13
- 91
- 116
-
1You cannot pass `ostream`s by value. – Kerrek SB Feb 04 '12 at 17:16
-
Possible Duplicate: http://stackoverflow.com/questions/4989483/where-to-put-default-parameter-value-in-c – Karine Feb 04 '12 at 17:17
-
1Don;t use the terms header of *.cpp (as stuff can be mixed around in these). But rather `declaration` and `definition`. Default arguments go in the `declaration`. – Martin York Feb 04 '12 at 18:31
4 Answers
You'll need to make the parameter into a reference parameter, you shouldn't try to copy std::cerr
. You probably need to specify the default parameter in the header file so that it's visible to all clients of the class.
e.g.
class MyClass {
public:
MyClass(char*, char*, std::ostream& = std::cerr);
// ...
};

- 755,051
- 104
- 632
- 656
-
Yep. I just realized that. Hm. Thanks for the prompt response. Off to the next problem! (now I'm getting segfaults. Woot.) (for another reason). – Linuxios Feb 04 '12 at 17:21
Default arguments are specifed when the function is declared: the header file in this case.

- 120,187
- 20
- 207
- 252
The header file is where you declare the defaults.
functionname(char *arg1, char* arg2, ostream &arg3 = cerr);
And then in the cpp file you'd simply expect it to be there:
functionname(char *arg1, char* arg2, ostream &arg3) {
}
IE, do NOT put it in the .cpp file.

- 21,735
- 2
- 38
- 69
C++ uses the separate compilation. Each cpp file is compiled separately. If you default values in cpp it will work OK, but this default values will be seen only in cpp file.
When include header file in other files of your project compiler determinates all information it needs from header file. If the defaults values are cpp file, other parts of your project can't look into cpp files, as they may be already compiled. So in almost all cases the default values should be kept in header file.
The other problem you can't put default values in both cpp and h file, as while compiling the cpp file compiler would not be able to choose which defaults values should be used and you will have compilation error.
You solution is (in header file):
class MyClass
{
public:
MyClass(char*, char*, ostream& = cerr);
...
};
In some rare cases you may specify default values in cpp file, if you want only this file to see and use them while all other parts of the project would not be able to do this. But this happens very rarely.

- 3,319
- 2
- 31
- 37