Question

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;
}
Was it helpful?

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;

OTHER TIPS

Chest chest();

Is not as you might believe, a call to the constructor

Chest::Chest();

But rather the declaration of a function. The proper way to create your chest is

Chest chest;

It is only when you have defined constructors that takes arguments you should use the parenthesis.

string s;
string s2("Hello");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top