Search code examples
c++parametersdefault-parameters

Is there any way to set parameter default as function of previous parameter? [C++]


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) { ... }

Solution

  • 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);
    }