making an argument optional?

Jan 16, 2011 at 5:33am
closed account (4Gb4jE8b)
I have a function

void type_erase(std::string content, int placement, int backspace, double time_delay)

but i want to include an optional argument like so

void type_erase(std::string content, int placement, int backspace, double time_delay, OPTION)

can i do so without copy/pasting the entire function? Lets say that OPTION is specifically an int. and if so, generally speaking, how would i do so?
Last edited on Jan 16, 2011 at 5:33am
Jan 16, 2011 at 6:02am
Here is an example void foo ( int a, int b = 0 )
There 'a' is a normal parameter, 'b' is optional, if no value is passed for 'b', 0 will be used for it
After you declare an optional parameter, all following parameters must be optional too
If you have the prototype and implementation of the function in two separate places, you must specify the default value only in the prototype
eg
1
2
3
4
5
6
void foo ( int a, int b = 0 ); // or void foo ( int , int = 0 )

void foo ( int a, int b )
{
     //...
}
Jan 16, 2011 at 6:17am
Like bazzy said. Just use default parameters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int count_to(int top, int steps = 1)
{
   for (int i = 0; i < top; i+=steps)
      std::cout << i << std::endl;

   return 0;
}

int main()
{
   count_to (10);
   count_to(100, 10);
}
Jan 16, 2011 at 6:19am
closed account (4Gb4jE8b)
THANK YOU! that's exactly what i needed
Topic archived. No new replies allowed.