Default value for a string

  • Thread starter magnus.moraberg
  • Start date
M

magnus.moraberg

Hi,

I have the following function -

void SaveFile(string fileName = default)
{
if(fileName.empty())
file.Save();
else
file.Save(fileName);
}

What should "default" be so that I can do the following -

SaveFile(); or
SaveFile("fileName");

Or must I have no default and do the following instead -

string dummy;
SaveFile(dummy);

Thanks for your help,

Barry
 
T

Tyler McHenry

Hi,

I have the following function -

void SaveFile(string fileName = default)
{
  if(fileName.empty())
    file.Save();
  else
    file.Save(fileName);

}

What should "default" be so that I can do the following -

SaveFile(); or
SaveFile("fileName");

It should be the empty string: ""

SaveFile() will then be equivalent to SaveFile(""), which seems to be
what you want.

Be careful not to double-define your defaults. If there is a prototype
for SaveFile somewhere in your code, put the default there, and leave
it out in the implementation.
 
D

DerTopper

Hi,

I have the following function -

void SaveFile(string fileName = default)
{
  if(fileName.empty())
    file.Save();
  else
    file.Save(fileName);

}

What should "default" be so that I can do the following -

SaveFile(); or
SaveFile("fileName");

Your question is a bit ambigues: Are you interested in how to provide
a standard value for the parameter of SaveFile, or are you interested
in which value should be passed? The second meaning is, of course,
highly dependent on your project, so we can't answer it here. If you
are interesting in how to provide such a standard value, Mr. McHenry
has already answered it sufficiently. I just want to add that you
should declare SaveFile in the following way:

void SaveFile(const std::string& fileName = "");

This declaration can be used in a header file (in header files all
entities should be explicitely qualified with the namespace they
belong to, it's an absolute Don't to have "using namespace" statements
in headers), and the parameter won't be copied (you probably don't
want a copy of the file name).

Regards,
Stuart
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,278
Latest member
BuzzDefenderpro

Latest Threads

Top