zennehoy
zennehoy

Reputation: 6846

Getting default constructor and initializer list to work side by side

I have been using initializer lists to instantiate instances of a struct, but would now like to add a default constructor.

struct Size {
    unsigned int width;
    unsigned int height;
};

void SizeFunc(Size const &size) { }

int main() {
    SizeFunc({1024, 768});   // OK.
}

Unfortunately, adding a default constructor causes an error when instantiating with the initializer list.

struct Size {
    Size() : width(1920), height(1080) { }

    unsigned int width;
    unsigned int height;
};

void SizeFunc(Size const &size) { }

int main() {
    Size size; // OK.
    SizeFunc({1024, 768});    // error: no matching function for call to
                              // 'Size::Size(<brace-enclosed initializer list>)'
}

What constructor do I need to add for this to work? I've tried using constructors with std::initializer_list, but have had no success so far.

Upvotes: 1

Views: 99

Answers (1)

Sebastian Redl
Sebastian Redl

Reputation: 71899

Just add a non-explicit constructor taking two unsigned ints that initializes the members with the arguments.

Size(unsigned int width, unsigned int height) : width(width), height(height) {}

Upvotes: 4

Related Questions