Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when initializing a struct with a brace-enclosed initializer list

struct CLICKABLE
{
    int x;
    int y;
    BITMAP* alt;
    BITMAP* bitmap;

    CLICKABLE()
    {
        alt=0;
    }
};

CLICKABLE input={1,2,0,0};

This code gives me the following error:

Could not convert from brace-enclosed initializer list

Could someone explain me why the compiler is giving me this error, and how I can fix it? I'm still learning the language.

like image 251
user2390934 Avatar asked Jul 15 '14 06:07

user2390934


People also ask

What is brace initialization?

If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization: C++ Copy.

How to initialize struct members c++?

// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.

How to initialize an struct?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

How to initialize union in c++?

A union can have a constructor to initialize any of its members. A union without a constructor can be initialized with another union of the same type, with an expression of the type of the first member of the union, or with an initializer (enclosed in braces) of the type of the first member of the union.


1 Answers

Your class has a constructor, so it isn't an aggregate, meaning you cannot use aggregate initialization. You can add a constructor taking the right number and type of parameters:

struct CLICKABLE
{
  int x;
  int y;
  BITMAP* alt;
  BITMAP* bitmap;

  CLICKABLE(int x, int y, BITMAP* alt, BITMAP* bitmap) 
  : x(x), y(y), alt(alt), bitmap(bitmap) { ... }

  CLICKABLE() : x(), y(), alt(), bitmap() {}

};

Alternatively, you can remove the user declared constructors, and use aggregate initialization:

CLICKABLE a = {};         // all members are zero-initialized
CLICKABLE b = {1,2,0,0};
like image 200
juanchopanza Avatar answered Sep 17 '22 07:09

juanchopanza