Search code examples
c++initialization

Can't construct object because member doesn't have default constructor


When compiling my program, I am getting this error:

error: constructor for 'parser' must explicitly initialize the member 'lexer_inst' which does not have a default constructor

As the error mentions, my member "lexer_inst" doesn't have a default constructor. However, I don't want it to be default-constructed in the first place. I am writing to the member in the constructor anyway. It seems illogical to me that I wouldn't be able to keep the member uninitialized until I initialize it myself. In my case, I can't use the initializer list for my member because it depends on the value of another member that is being created in the constructor.

This is my constructor code:

parser::parser(source_file &file) : file(file) {
    this->ast_arena = arena(file.data.length * 4);
    this->lexer_inst = lexer(this->ast_arena, file);
}

How can I keep "lexer_inst" uninitialized? (It has the type "lexer", which actually has reference members and therefore can't be default initialized)


Solution

  • How can I keep "lexer_inst" uninitialized?

    You can’t, and you shouldn’t. Change your constructor to

    parser::parser(source_file& file)
        : file(file)
        , ast_arena(file.data.length * 4)
        , lexer_inst(ast_arena, file) {}
    

    That is, exclusively use the member initialiser list to set up your class, don’t attempt to push this initialisation into the constructor’s body.

    Make sure that your order of member declaration mirrors the order of the initialisation, otherwise the above will fail. Good compilers will warn you if that’s not the case.