c++constructorcompilationcompiler-errorstry-catch

Default Constructor Compilation error expected unqualified id


I want to build a Default Constructure which initializes my attribute (which is an instance), from a File using a method loadfile. I also want an exception thrown if the file could not be loaded and if that is the case, I need to call my reset() function.

For the following code I always get the same error, at the try line, when trying to compile.

Env.cpp:16:8: error: expected unqualified-id before 'try'

Env::Env() **// default constructor of Env class**
: terrain **// terrain is an instance of a class I declared in hpp file**
{
try
    {Env::loadFile();} **// the method loadfile throws an error it failed**
catch(std::runtime_error)
    {std::cerr << " Error " << endl;
        Env::reset();} **// calls reset function if file loading failed**
}

Solution

  • The compiler thinks The { try ... } is a brace-init-list for terrain. If you meant to default-construct it, do it like this:

    : terrain{}
    {
        ...
    

    or this:

    : terrain()
    {
        ...
    

    or omit the whole member initialization list if terrain is an instance of a class.