I want to create a class, which has two integer member variables, and a function which has two optional arguments. If these arguments are supplied, the function returns the sum of them; if these arguments are not supplied, the function returns the sum of its two member variables.
Here is the code:
class Foo
{
private:
int x_;
int y_;
public:
Foo(int x, int y) : x_(x), y_(y){}
int Bar(int a = x_, int b = y_)
{
int z = a + b;
return z;
}
};
However, I get the following compilation error:
invalid use of non-static data member 'Foo::x_'
int x_;
^
invalid use of non-static data member 'Foo::y_'
int y_;
^
This suggests that the member variables have to be static to use them in as default arguments in a function. But I do not want them to be static...
What is the solution?
Overload Bar
:
int Bar()
{
return x_ + y_;
}
int Bar(int x)
{
return x + y_;
}
int Bar(int x, int y)
{
return x + y;
}
Thanks to @Jarod42 for this improvement:
int Bar(int a, int b)
{
return a + b;
}
int Bar(int a)
{
return Bar(a, y_);
}
int Bar()
{
return Bar(x_, y_);
}
The real-world problem you're trying to solve is more likely to benefit from this refactoring than the original problem of summing two numbers. This behavior is more obviously identical to that you were hoping to achieve through default arguments.
A workaround would be to overload your Bar
function as:
int Bar()
{
return x_ + y_;
}
int Bar(int a)
{
return a + y_;
}
int Bar(int a, int b)
{
return a + b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With