I'd like to have a function with an optional parameter but without overloading the function. The reason I don't want to overload is because the function body is quite long, and the version with the optional parameter just differs by a single line.
void myFunction(MyClass my_optional_arg = MyClass())
{
// lots of statements
if (optional_argument_was_passed)
doSomething(my_optional_arg);
// lots more statements
}
int main()
{
myFunction();
MyClass my_optional_object();
myFunction(my_optional_object);
}
The problem that I have with the default parameter route is that I don't know how to check whether the optional parameter was passed or not, i.e., I don't know how to set the boolean flag optional_argument_was_passed
. For example, just testing equality of the parameter with the default isn't sufficient because that same default value could be passed into the function. What I'd really like is something like this:
void myFunction(MyClass my_optional_arg = some_unique_null_value)
{
// lots of statements
if (my_optional_arg != some_unique_null_value)
doSomething(my_optional_arg);
// lots more statements
}
It has been suggested that I do something like this:
void myFunction()
{
MyClass my_object();
myFunction(my_object);
}
However, this is not quite what I need; the myFunction(MyClass)
function is not necessarily the ultimate function to be used. If I call the function without the optional argument, myFunction()
, then I don't want any object of class MyClass
to even enter the function at all; rather, the statement that uses this object, called doSomething(MyClass)
above, should be omitted.
It has also been suggested that I remove the common parts of both functions to its own function myFunction()
and then create an overloaded wrapper function to call the statements with the optional parameter:
void myFunction(MyClass my_optional_arg)
{
doSomething(my_optional_arg);
myFunction();
}
This is a solution, but it would be a bit messy because I have a lot of statements before AND after the doSomething(MyClass)
call, so I'd need to split the function into several parts:
void myFunction(MyClass my_optional_arg)
{
myFunctionPartA();
doSomething(my_optional_arg);
myFunctionPartB();
}
void myFunctionPartA()
{
// lots of statements
}
void myFunctionPartB()
{
// lots more statements
}