'Initializing an object as in a vector class [closed]

So, I know a vector object can be declared and initialized like this:

// Nothing new here. I know <int> is a template
// and how to implement it:

vector <int> vect{ 10, 20, 30 };

I assume that the vector object has inside an array of values, and the functions of that class (like push_back() for example) manage it. I would like and have been trying to implement something like that in a class of my own, without success. Would be interesting being able to understand how it's done! Did many "experiments" but none worked.

// Random named class:
class A_Class
{
private:

    // A pointer for the type I want:
    int *A_pointer_To_int;

public:
    // Trying to accept the input values between
    // brackets and putting them inside a temp array:
    A_Class(int Input_Array[]) {}

};

int main()
{
    // trying to create the object like in the vector class.
    // Returns error "No instance of constructor matches the argument list":

    A_Class My_Object{1,2,3}

    return 0;
}


Solution 1:[1]

In a function parameter, int Input_Array[] is just syntax sugar for a decayed pointer int* Input_Array, which does not provide any information about any array that may be passed in to it.

For what you are attempting, you need to accept a std::initializer_list instead, eg:

#include <initializer_list>
#include <algorithm>
        
// Random named class:
class A_Class
{
private:

    // A pointer for the type I want:
    int *A_pointer_To_int;

    // the number of values in the array:
    size_t size;

public:
    A_Class(std::initializer_list<int> Input_Values) {
        size = Input_Values.size();
        A_pointer_To_int = new int[size];
        std::copy(Input_Values.begin(), Input_Values.end(), A_pointer_To_int);
    }

    ~A_Class() {
        delete[] A_pointer_To_int;
    }
};

int main()
{
    A_Class My_Object{1,2,3}; // works now

    return 0;
}

Online Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau