Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why am i getting a "no instance of constructor matches the MyArray::MyArray" argument list?

Tags:

c++

#include <iostream>
#include <initializer_list>

class MyArray {
    int* array;
public:
    MyArray(){}
    MyArray(std::initializer_list<int>& v) {
        array = new int[v.size()];
        int index = 0;
        for (auto element : v) {
            array[index] = element;
            index++;
        }
    }

    ~MyArray()
    {
        delete[] array;
    }
};

int main() {
    MyArray object{ 2,4,2,2 };
}

This is my first time working with std::initializer for object list initialization. I have created a an array that is initialized using the MyArray constructor. i don't know where am i going wrong. i created an object that matches the argument list, ie a constructor that takes an initializer list.

like image 357
kira55 Avatar asked Dec 04 '25 00:12

kira55


1 Answers

i created an object that matches the argument list, ie a constructor that takes an initializer list.

You didn't; not quite.

You created a constructor that takes a reference to an std::initializer_list.

But one created in this manner is [possibly] a temporary that cannot bind to such a reference.

Generally you just want to take std::initializer_lists by value. That is: remove the &.

There are some examples on cppreference's article on std::initializer_list.

like image 71
Lightness Races in Orbit Avatar answered Dec 06 '25 14:12

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!