Mohamed Ali Mohamed Ali - 5 months ago 29
C++ Question

How to pass optional parameter to a method in C++?

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;
void Main(){ func(b:5,c:6);}


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.