Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default arguments as non-static member variables

Tags:

c++

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?

like image 810
Karnivaurus Avatar asked Sep 04 '15 13:09

Karnivaurus


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 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.

like image 137
Austin Mullins Avatar answered Oct 09 '22 01:10

Austin Mullins


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;
}
like image 34
Logicrat Avatar answered Oct 09 '22 01:10

Logicrat