Reputation: 35783
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?
Upvotes: 1
Views: 2656
Reputation: 3600
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.
Upvotes: 0
Reputation: 22252
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.
Upvotes: 1
Reputation: 791641
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);
// ...
};
Upvotes: 9
Reputation: 121961
Default arguments are specifed when the function is declared: the header file in this case.
Upvotes: 1