1

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?

3
  • 1
    You cannot pass ostreams by value. Commented Feb 4, 2012 at 17:16
  • Possible Duplicate: stackoverflow.com/questions/4989483/… Commented Feb 4, 2012 at 17:17
  • 1
    Don;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. Commented Feb 4, 2012 at 18:31

4 Answers 4

9

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);
    // ...
};
Sign up to request clarification or add additional context in comments.

1 Comment

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).
1

Default arguments are specifed when the function is declared: the header file in this case.

Comments

1

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.

1 Comment

You cannot pass ostreams by value!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.