Home > Mobile >  Cannot instantiate class inside other class. Member Map::value is not a type name
Cannot instantiate class inside other class. Member Map::value is not a type name

Time:10-14

сlass Chunk
{
private:
    size_t value;
public:
    Chunk(size_t value)
    {
        this->value;
    }
};

class Snake
{
private:
    size_t value;
    std::vector<Chunk> snake_body;
public:
    Snake(size_t value) 
    {
        Chunk head_chunk(value);
        snake_body.push_back(head_chunk);
    }
};

class Map
{
private:
    size_t value;
                            // Not able to find "snake" definiton
    Snake snake(value);     // member Map::value is not a type name
    Snake snake { value; }  // Why it works?
}

I'm newbie in OOP, trying to learn it by creating a game console-snake. Here's a problem i met. Structure of the game should be that class Map holds one snake. But when i am trying to instantiate it, i get a problem. Spent so many time on SOF, but nothing have found yet. And why it works with {} Please help ;/

CodePudding user response:

Snake snake(value) is not valid syntax for initialization, and Snake snake{ value } is valid syntax(but probably initializes to an unitialized value since value is not initialized). Some more comments in code below :

class Map
{
public:
    // this is best if you want the main program to initialize snake with a user provided value
    explicit Map(size_t value) :
        snake{ value }              // aggregate initialization https://en.cppreference.com/w/cpp/language/aggregate_initialization
    {
    }

private:
    size_t value;           // if you use Snake{value} then also initialize value here, size_t value{0}; (or size_t value = 0;)
    // Not able to find "snake" definiton
    Snake snake(value);    //  <== this tries to make a call to the constuctor of Snake which can't be done here
    Snake snake{ value; }  // <== this is a valid initialization syntax, but uses unitialized value (so result can be any number)
}
  • Related