'Setting default value for Bool by reference

How do i assign a default value to a bool that is a reference?

I have a function like this :

void someFunction(bool a = true, bool& b)
{
 if(a)
   b = false;
 else
   std::cout << "nothings changed" << std::endl;
}

How should i assign the default value to b in this context?

void someFunction(bool a = true, bool& b = false)

will not work. So how should it be done?



Solution 1:[1]

You cannot initialize non-const references with values. You need a variable:

bool dummy_variable;

void someFunction(bool a = true, bool& b = dummy_variable)
{
    // ...
}

But it would probably make a lot more sense to simply return the bool:

bool someFunction(bool a = true)
{
    return !a;
}

Then the client can still decide for himself if he wants to ignore the result or not.

Solution 2:[2]

You cannot bound temporary object to a non-const reference. You need to use non-temp object:

bool bDefaultVal = false;

void someFunction(bool a = true, bool& b = bDefaultVal)
{
    ...
}

Solution 3:[3]

Why not use a pointer?

#include <iostream>

using namespace std;

void someFunction(bool a = true, bool* b = nullptr)
{
    if (b != nullptr) {
        *b = a; 
    }
}

int main()
{
   bool res = true;
   someFunction();
   cout << res << endl; // true
   someFunction(false);
   cout << res << endl; // true
   someFunction(false, &res);
   cout << res << endl; // false

   return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fredoverflow
Solution 2 Bojan Komazec
Solution 3 Joaquim Varandas