Constructor using {a,b,c} as argument or what is {a,b,c} actually doing

  • A+
Category:Languages

I know, that I can initialize data like this.

int array[3] = { 1, 2, 3 }; 

or even

int array[2][2] = { {1, 2}, {3, 4} }; 

I can also do it with std::vector

std::vector<int> A = { 1, 2, 3 }; 

Let's say I want to write my own class:

class my_class {      std::vector< int > A;      public:      //pseudo code            my_class(*x) { store x in A;} //with x={ {1, 2}, {3, 4} }      //pseudo code }; 

Is it possible to write such a constructor and how is it possible? What is this statement "{{1, 2}, {3, 4}}" actually doing. I always just find, that you can initialize data in this way, but never what it is doing precisely.


It is called list initialization and you need a std::initilizer_list constructor, that to be achieved in your my_class.

#include <iostream> #include <vector> #include <initializer_list>  class my_class {     std::vector<int> A; public:     // initilizer_list constructor      my_class(const std::initializer_list<int>& v) : A(v) {}       friend std::ostream& operator<<(std::ostream& out, const my_class& obj); }; std::ostream& operator<<(std::ostream& out, const my_class& obj) {     for(const auto& it: obj.A) out << it << " ";     return out; }  int main() {     my_class obj = {1,2,3,4};  // now possible     std::cout << obj << std::endl;     return 0; } 

LIVE DEMO

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: