Re: How to: optional CString parameter
On Sun, 4 May 2008 17:06:35 -0400, "Jeov? Almeida" <jeovaalmeida@yahoo.com>
wrote:
Hello,
How can I make a CString parameter optional?
I tried
[in the .h file:]
virtual CString Get(CString strURL, CString& strErrorMsg = NULL);
It gives me the error
Error 4 error C2440: 'default argument' : cannot convert from 'int' to
'CString &
Right, there is no such thing as a null reference in C++. If you want the
null concept, you'll have to use pointers.
What I want to do: make the strErrorMsg parameter optional so I could call
CString result = obj.Get("www.server.com");
CString errMsg;
CString result2 = obj.Get("www.server.com", errMsg);
Though not quite the same as NULL, you could use:
virtual CString Get(
CString strURL, // If you don't modify, use a const reference.
const CString& strErrorMsg = CString());
But I wouldn't use default parameters with a virtual function. A better
approach would be:
CString Get(
CString strURL,
const CString& strErrorMsg = CString())
{
return Get_impl(strURL, strErrorMsg);
}
virtual CString Get_impl(
const CString& strURL,
const CString& strErrorMsg);
The other reason to use this technique is to avoid overloading virtual
functions, which reduces the burden on derived classes that want to
override the virtual function. Finally, if the parameters don't /need/ to
be CStrings, use LPCTSTR parameters. That way, when you say...
CString result = obj.Get("www.server.com");
.... you don't needlessly construct a temporary CString to represent the
parameter.
--
Doug Harrison
Visual C++ MVP