Constructor using {a,b,c} as argument or what is {a,b,c} actually doing?
It is called list initialization and you need a std::initilizer_list constructor, that to be achieved in your my_class
.
See (Live Demo)
#include <iostream>
#include <vector>
#include <initializer_list> // std::initializer_list
class my_class
{
std::vector<int> A;
public:
// std::initilizer_list constructor
my_class(const std::initializer_list<int> v) : A(v) {}
friend std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */;
};
std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */
{
for(const int 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;
}
You can use initializer_list in the constructor to have such option.
struct X {
X() = default;
X(const X&) = default;
};
struct Q {
Q() = default;
Q(Q const&) = default;
Q(std::initializer_list<Q>) {}
};
int main() {
X x;
X x2 = X { x }; // copy-constructor (not aggregate initialization)
Q q;
Q q2 = Q { q }; // initializer-list constructor (not copy constructor)
}
how is it possible?
If you have an initializer list.
#include <initializer_list> // use std::initializer_list template
my_class(const std::initializer_list<int>& v) : A(v) {}
What is this statement "{{1, 2}, {3, 4}}" actually doing?
This is called list-initialization
If the initializer is a (non-parenthesized) braced-init-list or is
=
braced-init-list, the object or reference is list-initialized.