As mentioned in the other answers, NULL references aren't allowed in C++, so you can't use NULL as a default value for a by-reference argument, and std::optional
would be a good choice instead.
You can define your own sentinel-object though, to perform the same function as NULL without actually being a NULL-reference, like this:
#include "stdio.h"
const int & get_sentinel_ref()
{
static int sentinel = 0; // must be declared static
return sentinel; // in order to have a fixed address
}
void test(int a, const int &b = get_sentinel_ref())
{
// Check if b is referring to our sentinel-value or not
// Note that I'm comparing memory-addresses here, not values
// otherwise the code would do the wrong thing if the user
// passed in zero (or whatever dummy-value sentinel is set
// to in the get_sentinel_ref() function above)
if (&b == &get_sentinel_ref())
{
printf("a is %i, but you didn't supply a second argument!\n", a);
}
else
{
printf("a is %i, b is %i\n", a, b);
}
}
int main(int, char **)
{
test(5);
test(6,7);
return 0;
}
... When run, the above program prints:
a is 5, but you didn't supply a second argument!
a is 6, b is 7