Search code examples
c++compiler-errorsmost-vexing-parse

structure expected on left side of . or .* but it is a structure


I'm getting the compile error structure required on left side of . or .* on chest.contents[0], but chest is a structure:

class Item {
public:
    int id;
    int dmg;
};

class Chest {
public:
    Item contents[10];
};

int main() 
{
    Chest chest();

    Item item = chest.contents[0];

    return 0;
}

Solution

  • No it isn't, it's a function that takes zero parameters.

    To default-initialize a variable, use

    Chest chest;
    

    In C++11, this syntax can be used for value-initialization.

    Chest chest{};
    

    In C++03, that needs a complicated (because of many compiler bugs) workaround, which the Boost library thankfully has made easy to use:

    boost::value_initialized<Chest> chest;