Default Parameter

What is default parameter? Can a overloaded function have a default parameter?

Questions by jitesh jhajhria

Showing Answers 1 - 12 of 12 Answers

dipuprits

  • Apr 14th, 2009
 

Default parameter is a default value for a parameter to a function.
 
The default value can be provided to the list of parameters starting from the right end. Ex: for a function fun(int i, float f, long l), you can specify default value as fun( int i, float f, long l = 1000) but not fun( int i = 10, float f, long l).

You can specify default value for overloaded function provided it is still different from the other forms when the default value is applied.

Ex: void Fun( int i );
void Fun( int i, int j, float f);
void Fun( int i, int j = 10);   // Ambiguous call.

the third version is not allowed as the compiler cannot decided which of the two to use when there is a call to this function like Fun(10) since it could either be Fun(10) or Fun(10,10).

The overloads may not always be banned. The compiler could remove the parameter with default values for the overload resolution. e.g. The signature of the fuction after removing the default parameters should not match any other fuction signature.


Moreover the definition, may be still be allowed if there is no ambiguous call. The overload resolution may require help from the coder in that circumstance.

  Was this answer useful?  Yes

yzesong

  • Jul 29th, 2009
 

This is my answer, please correct me if I am wrong.

Overloading functions with default parameters will cause compile error for ambiguous calling on the overloaded function.  But it really depends on the signatures of the overloaded function. If you don't call the overloaded function, as long as the signatures are different, it compiles fine. When you call them, you can not omit all the parameters because of ambiguity issue. 

Here is an example I played with, 
void PrintValues(int nValue1=10, int nValue2=20, int nValue3=30)
{
using namespace std;
cout << "IValues: " << nValue1 << " " << nValue2 << " " << nValue3 << endl;
}

double PrintValues(double fValue1= 1.1, double fValue2=2.2, double fValue3=3.3)
{
using namespace std;
cout << "FValues: " << fValue1 << " " << fValue2 << " " << fValue3 << endl;

return 99.9;
}

int main(int argc, char* argv[])
{
PrintValues(1, 2, 3);
PrintValues(1, 2);
PrintValues(1);
//PrintValues();  // this will causing ambiguity

PrintValues(88.88); // this is fine

return 0;
}

So generally, you don't want to do this. 

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions