Friday, September 3, 2010

Default Argument Value for Methods

Like in C++, C#, PHP or SQL we can provide the default value for the argument that will be used in case when value is not supplied during method/function call. For example the following function declaration in C++:


void int someFun(int a, int b =0) {
// some implementation here...
}

In the above function the last argument has a default value of 0, and it will be used when we will call this function by providing only one parameter, like;
someFun(5);
The above function call will give value 5 to argument “a” and 0 for argument “b”.
The same function can be called to provide both of the values, like:
someFun(5,10);
Fortunately/Unfortunately you can not declare a function/constructor with default values for arguments because experts say this is a bad implementation design. If you have to achieve the same kind of functionality the better way is to declare overloaded methods and call one with default value in other. For example:

void int someMethod(int a, int b ) {
// some implementation here...
}
void int someMethod(int a) {
// call overloaded method with default value of the argument
someMethod(a, 0);
}

No comments: