invalid use of static data member in constructor parameter list

49 Views Asked by At

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.

2

There are 2 best solutions below

5
Ilya Popov On BEST ANSWER
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)

2
Israel Unterman On

When you call the constructor the object doesn't exist yes. It's the constructor that creates and returns it. So you can't refer to v1 in the arguments of the constructor - there is still no object and no v1.