Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

could not convert {...} from <brace-enclosed initializer list> to struct

I'd previously used TDM-GCC-5.10 and now switched back to 4.9 MINGW-GCC and getting a weird error with trying to use list-initialization:

class Vector2
{
public:
    Vector2(float x, float y)
    {
        this->x = x;
        this->y = y;
    }
    float x = 0.f;
    float y = 0.f;
};

struct Test
{
    int x = 0;
    Vector2 v;
};

int main()
{    
    Test tst = {0,Vector2(0.0f,0.0f)}; //Error
    return 0;
}

Error:

main.cpp: In function 'int main()':
main.cpp:21:41: error: could not convert '{0, Vector2(0.0f, 0.0f)}' from '<brace-enclosed initializer list>' to 'Test'
         Test tst = {0,Vector2(0.0f,0.0f)}; //Error
                                         ^

I used C++14 with both compilers. What is wrong?

like image 794
GamesTable Studio Avatar asked Jun 12 '16 16:06

GamesTable Studio


2 Answers

The problem is here:

struct Test
{
    int x = 0; // <==
    Vector2 v;
};

Until recently, default member initializer prevent the class from being an aggregate, so you cannot use aggregate initialization on them. Gcc 4.9 still implements the old rules here, whereas gcc 5 uses the new ones.

like image 189
Barry Avatar answered Oct 07 '22 16:10

Barry


You missed ; after your class definition and after int x = 0. Then you got many errors and apparently only considered the last one. But your compiler was confused because Vector2 was not defined (due to missing ;).

This compiles:

int main()
{
    class Vector2
    {
    public:
        Vector2(float x, float y)
        {
            this->x = x;
            this->y = y;
        }
        float x = 0.f;
        float y = 0.f;
    };

    struct Test
    {
        int x;
        Vector2 v;
    };

    Test tst = {0,Vector2(4,5)};
    return 0;
}
like image 3
jpo38 Avatar answered Oct 07 '22 15:10

jpo38