Search code examples
c++11non-staticdata-members

invalid use of static data member in constructor parameter list


I have a class something like this:

class Foo : public Bar {
double v1;
double v2;
...
public:
explicit Foo (double v1_ = 1.0, double v2_ = v1 > 0.0 ? 2.0 : 0.0)
    : v1(v1_), v2(v2_)
{
    // do something
}

// do other things

};

but I get the following compile error like so:

error: invalid use of non-static data member Foo::v1
note: declared here
double v1;
       ^

Any suggestions are appreciated to get around this error. Also, please point out the mistake in my code and explain a little so that I can understand better. Thanks in advance.


Solution

  • explicit Foo (double v1_ = 1.0, double v2_ = v1 > 0.0 ? 2.0 : 0.0)
                                                 ^^
    

    At the point where you use v1 it does not exist yet.

    Unfortunately, you can't use v1_ at this point either. What you can do instead, is to split the constructor in two versions:

    // for two arguments
    Foo (double v1_, double v2_)
        : v1(v1_), v2(v2_)
    {
        // do something
    }
    
    // for zero or one argument
    explicit Foo (double v1_ = 1.0)
        : Foo(v1_, v1_ > 0.0 ? 2.0 : 0.0)
    {
    }
    

    (here I used delegating constructors feature to avoid code duplication)