Search code examples
c++constructordefault-constructor

Not declared variable in default-constructed object in constructor


The above code doesn't work. Indeed the default constructed object f in the constructor of Foo complains that the value val is not declared in the scope. I don't understand why it is not declared.

struct Foo2
{
  Foo2(int val)
  {}
};

struct Foo
{
  Foo(int val, Foo2 f = Foo2(val))
  {}
};

int main()
{
  Foo f(1);
  return 0;
}

Solution

  • According to the C++ Standard (8.3.6 Default arguments):

    9 Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.

    In any C++ (not only C++ 2014) you can overload the constructor. For example

    struct Foo
    {
      Foo(int val )
      { Foo2 f(val); /*...*/ }
      Foo(int val, Foo2 f )
      {}
    };
    

    Or you can use a delegating constructor (if your compiler supports the new Standard)

    struct Foo
    {
      Foo(int val ) : Foo( val, Foo2( val ) )
      {}
      Foo(int val, Foo2 f )
      {}
    };