A simple example of a list of initializers

I am looking for a simple example of using a list of initializers. Here is what I want to do: I have the following class:

class foo{
    public:
        void set_x(const int ix);
        void set_y(const int iy);
        void display();
    private:
        int x;
        int y;
};

I would like to create an object of this class as follows:

foo fooObj = {1, 2};

I know this is possible with a vector in C ++ 11. How can I implement this behavior?

+4
source share
1 answer

In this case, a simple constructor will work:

foo(int x, int y) : x(x), y(y) {}

If the class was an even simpler aggregate (which you would have if the data members were publicly available), then you do not even need to - this initialization style will initialize each member of the aggregate in turn.

- , vector, , initializer_list. :

#include <initializer_list>

foo(std::initializer_list<int>);

, begin(), end() size() .

+6

All Articles