Where should I write the default parameter in the function declaration/definition?

Asked 2 years ago, Updated 2 years ago, 23 views

Where should I write the default parameter? In the function declaration? In the function definition? Or both?

The code that people wrote down I think they all wrote whatever they wanted Is there any rule?

c++ default-argument

2022-09-22 13:26

1 Answers

The default parameter must appear in the function declaration. That way, you can see it when you call a function from another location.

If you declare the header file without default parameters, If you write the default parameter while defining the function in A.cpp Other places, such as B.cpp, do not know that the default parameter is present.

//myheader.hpp

void myfunc(int nonDefault, float Default);

/******* File sharing ********/

//A.cpp

int myfunc(int nonDefaultParam, float DefaultParam=3){
    cout << "hello" << endl;
    return 1;
}

void funcA(){
    myfunc(3); //ok
    myfunc(3, 3.0); //ok
}


/******* File sharing ********/

//B.cpp

void funcA(){
    myfunc(3); //error!!!!!!!!!!!
    myfunc(3, 3.0); //ok
}


2022-09-22 13:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.