Search code examples
c++initializationinitializer-listlist-initialization

How to initialize an object of a class using curly brackets {}


I'm looking to make this code compiled with no error (and without using std::initializer_list) Here's the code :

template<typename T>
class Vector {
public:
    T* Arr;
    int Size = 0;
    int Capacity = 1;
    Vector();
};

template<typename T>
Vector<T>::Vector() {
    Arr=new T[1];
}
int main()
{
    Vector<int>V1 = { 1,2,3,4,5 };
}

Here's the Error :

Error C2440: 'initializing': cannot convert from 'initializer list' to 'Vector<int>'

Solution

  • How to initialize an object of a class using curly brackets {}

    Vector<int>V1 = { 1,2,3,4,5 };
    

    Option 1: Use std::initializer_list.

    (and without using std::initializer_list)

    Well, then use one of the other options:

    Option 2: Make the class an aggregate. You initialise the members of the class with {x, y, z}. This approach is incompatible with your example.

    Option 3: Use a variadic template constructor such as:

    template<class... Args>
    Vector(Args&& ...args)