Reputation: 23
How to pass optional parameters to a method in C++ ?
is there a way like in C# we can use this statement Func(identifier:value) which allow me to pass value to any parameter i want .... for example:
//C# Code
void func(int a=4,int b,int c)
{
int sum=a+b+c;
Console.Write(sum);
}
void Main(){ func(b:5,c:6);}
Upvotes: 1
Views: 216
Reputation: 56
Yes, but, short answer is that a parameter with a default value cannot precede parameters which don't get defaults. So:
void func(int a=4,int b,int c) {} //doesn't work
void func(int b, int c, int a = 4){} //works
See http://en.cppreference.com/w/cpp/language/default_arguments for more information
Upvotes: 2
Reputation: 15164
Yes, but you can only do it to the rightmost elements. So you could write void func(int a, int b, int c=4)
or void func(int a, int b=2, int c=4)
or even void func(int a=1, int b=2, int c=4)
, but not the example you gave.
Upvotes: 1
Reputation: 303947
In C++, default arguments have to go last, so you would write:
void func(int b, int c, int a=4)
{
int sum = a+b+c;
std::cout << sum;
}
int main() {
func(5, 6); // b = 5, c = 6, a uses the default of 4
}
You cannot provide named parameters all the call site the way you can in C# or Python. There is a boost library to fake support for naming parameters, but I've never used it.
Upvotes: 5