httpinterpret httpinterpret - 1 year ago 148
C++ Question

Default value of function parameter


int Add (int a, int b = 3);
int Add (int a, int b)



int Add (int a, int b);
int Add (int a, int b = 3)


Both work,which is the standard way and why?

Answer Source

If you put the declaration in a header file, and the definition in a separate .cpp file, and #include the header from a different .cpp file, you will be able to see the difference.

Specifically, suppose:


int Add(int a, int b);


int Add(int a, int b = 3) {


#include "lib.h"

int main() {

The compilation of test.cpp will not see the default parameter declaration, and will fail with an error.

For this reason, the default parameter definition is usually specified in the function declaration:


int Add(int a, int b = 3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download