views:

61

answers:

1

I assume not, but I just wanted to check - is there any way in C++ to do something like the following? Obviously when I try the below I get a scope-based error about bar.

void foo(Bar bar, int test = bar.testInt) { ... }
+7  A: 

If there is a value of test that is invalid, you could detect that:

void foo(Bar bar, int test = -1) { //assuming -1 is invalid
    if(test == -1) test = bar.testInt;

    //...
}

If not, you could always use overloaded functions:

void foo(Bar bar, int test) {
    //...
}

void foo(Bar bar) {
    foo(bar, bar.testInt);
}
Mike Caron
+1 for function overloading, default parameters are not always the answer
meagar
So, as a further question, is there a 'right' answer out of these two? I don't know which I would find more readable... (Also, btw Mike, I don't think you meant to have `//assuming -1 is invalid` on the last two code segments.)
Stephen
Derp, that's what I get for copying and pasting! Anyway, I would probably go with the function overloading. However, I would also change `bar` to be a reference in that case, to avoid making so many copies of the object
Mike Caron
@Stephen - the former isn't always possible (values for test maybe cover the entire range), so I'd go with the latter.
Niki Yoshiuchi
@Stephen yes there is. The second one.
glowcoder
I think the first is generally what you'd go with in a language that doesn't allow function overloading.
UncleBens