Any way to call default variable values without specifying them?

I'm doing integrity checks on variables before initialising them; if they fail the checks I want them to be set to the default value. So that I don't have to edit two different sections of code (e.g. in the .h and .cpp files of a class) if I want to change the value later, is there any "set as default" function that I can call within the body of a set method?

Not exactly an urgent issue, of course, but it'd be good to know.
if I want to change the value later, is there any "set as default" function that I can call within the body of a set method?

That depends on whether you created such a function.

class.h:
1
2
3
4
5
6
7
void set_percentage(int newPercentage)
{
  if (newPercentage<0 || newPercentage>100)percentage=get_default_percentage();
  else percentage=newPercentage;
}

static int get_default_percentage();


class.cpp:

1
2
3
4
int myClass::get_default_percentage()
{
  return 0;
}


It doesn't necessarily have to be a function, nor does it need to be static.
Last edited on
I was talking about the default value that can be written in the method signature.

Based on your example, in a .h file for a class I might have a method header:

void set_percentage(int newPercentage = 50);

Where 50% is the default. In your above method, therefore, is there a way to change the "else" action so that I can retrieve that value (short of recursively calling the method with no value specified, i.e. set_percentage(); )?

Basically I want to know whether that number 50 can be accessed, so that I can simply change its value the .h file without having to touch the actual implementation.
No, you can't unfortunately...although you could just call the function with no arguments if you get a bad value:

1
2
3
4
int my_set_percentage(int new_value) {
    if(new_value > 0 && new_value < 100) set_percentage(new_value);
    else set_percentage();
}
Fair enough, just thought I'd asked. Thanks for your help.
Topic archived. No new replies allowed.