Programming & Scripting Tutorials

C++: Default Parameters





As well as overloading functions and constructors, you can set default parameters.
What these do is if the parameter isn't passed, it will just set it to the default(as you may have guessed this may interfere with overloading).
For example when we do normal function like the following if you don't specify the parameters it wont call that function, this is why we can overload functions.
For example

int Function1(int x){
return x;
}

But if we assign a default parameter if you don't specify that parameter the default value will kick in.
For example:

int Function1(int x = 10){
return x;
}

The following application would output 2, and then 10:

#include <iostream>
using namespace std;

int Function1(int x = 10){
return x;
}

int main(){
cout << Function1(2) << endl;
cout << Function1() << endl;
system("PAUSE");
return 0;
}

We can specify default values for as many parameters as we like, for example:

#include <iostream>
using namespace std;

int Function1(int x = 10, int y = 5){
return x + y;
}

int main(){
cout << Function1(1, 4) << endl;
cout << Function1(2) << endl;
cout << Function1() << endl;
system("PAUSE");
return 0;
}

Default parameters can however interfere with overloading functions as if you created a function with one parameter which specifies a default values, and have also created a different function which actually takes no parameters; the program will not know which function to use.

This C++ tutorial was written by


Back to C++

Advertisement: