Default Arguments as Non-Static Member Variables

I want to create a class that has two integer member variables and a function that has two optional arguments. If these arguments are provided, the function returns their sum; if these arguments are not provided, 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 member variables must be static in order to use them as default arguments in a function. But I do not want them to be static ...

What's the solution?

+6
source share
2 answers

Overload Bar :

 int Bar() { return x_ + y_; } int Bar(int x) { return x + y_; } int Bar(int x, int y) { return x + y; } 

Thanks @ 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 problem you are 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 what you hoped to achieve with the default arguments.

+6
source

A workaround would be to overload your Bar function as follows:

 int Bar() { return x_ + y_; } int Bar(int a) { return a + y_; } int Bar(int a, int b) { return a + b; } 
+5
source

All Articles