Default parameter question

Hi, I was wondering for default parameter values, if we could set a default value to be the return value of a function. Specifically, I'm asking if I can do this:

DerivedClass(const char* str, int l = (strlen(str)))

The above is a constructor for a class. I'm currently getting a "'str' is an undeclared identifier" error in Visual Studio when I try to do this. What is the correct syntax?

Also, if something like the above is possible, should I be doing this in the header file or implementation file?

Many thanks!
You can only have constants as default params. You cannot call functions or use non-const variables for them.

If you want to do that, instead of having a default param you overload the ctor and have them call a common "Construct" function

1
2
3
4
5
6
7
DerivedClass(const char* str, int l) { Construct(str,l); }

DerivedClass(const char* str) { Construct(str,strlen(str)); }

private:

void Construct(const char* str, int l) { ... }


As for whether it goes in the .h or the .cpp file, that depends on whether you want it inlined or not. My general rule is that if the function is small I inline it (put it in the header).
Thank you very much for your reply. That solved my problem completely!
Topic archived. No new replies allowed.