tags:

views:

148

answers:

5

hi,

How to pass optional parameters to a method in C++ ? Any code snippet...

+1  A: 

With commas separating them, just like parameters without default values.

int func( int x = 0, int y = 0 );

func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0

func(1, 2); // provides optional parameters, x = 1 and y = 2
Ben Voigt
+2  A: 

Typically by setting a default value for a parameter:

int func(int a, int b = -1) { 
    std::cout << "a = " << a;
    if (b != -1)        
        std::cout << ", b = " << b;
    std::cout << "\n";
}

int main() { 
    func(1, 2);  // prints "a=1, b=2\n"
    func(3);     // prints "a=3\n"
    return 0;
}
Jerry Coffin
+2  A: 

Here is an example of passing mode as optional parameter

void myfunc(int blah, int mode = 0)
{
 if(mode == 0)
  do_something();
 else
  do_something_else();
}

you can call myfunc in both ways and both are valid

myfunc(10); //mode will be set to default 0
myfunc(10, 1);//mode will be set to 1
JapanPro
Can you pls provide some example related to string ?
Swapnil Gupta
void myfunc(int blah, char mode[] = NULL)
JapanPro
`NULL` means a NULL pointer, even though it would be defined as literal `0`. It is not a universal name for constant zero. For integers (non-pointers) you should use numbers: `int mode = 0`.
UncleBens
@uncle thats right and thanks fredoverflow
JapanPro
+5  A: 

Use default parameters

template <typename T>
void func(T a, T b = T()) {

   std::cout << a << b;

}

int main()
{
    func(1,4); // a = 1, b = 4
    func(1);   // a = 1, b = 0

    std::string x = "Hello";
    std::string y = "World";

    func(x,y);  // a = "Hello", b ="World"
    func(x);    // a = "Hello", b = "" 

}

Note : The following are ill-formed

template <typename T>
void func(T a = T(), T b )

template <typename T>
void func(T a, T b = a )
Prasoon Saurav
+1  A: 

An important rule with respect to default parameter usage:
Default parameters should be specified at right most end, once you specify a default value parameter you cannot specify non default parmeter again. ex:

int DoSomething(int x, int y = 10, int z) -----------> Not Allowed

int DoSomething(int x, int z, int y = 10) -----------> Allowed 
Als
what is rightmost in case of variable number of arguments?
Chubsdad
@Chubsdad - Ahh..my bad ambigious statement! does the second statement sums it correctly? "once you specify a default value parameter you cannot specify non default parmeter again"
Als