First, consider basic construction. It sounds like you just want to create a new TestClass
and specify its initial values on-the-fly.
You can do this by using a constructor:
/**
* TestClass.hpp
*/
class TestClass
{
public:
int a;
int b;
TestClass(int aInitial, int bInitial);
};
/**
* TestClass.cpp
*/
TestClass::TestClass(int aInitial, int bInitial)
: a(aInitial),
b(bInitial)
{
}
// ... which is the same as...
TestClass::TestClass(int aInitial, int bInitial)
{
this->a = aInitial;
this->b = bInitial;
}
/**
* SomewhereElse.cpp
*/
...
TestClass foobar(1, 2);
std::cout << foobar.a << std::endl; // 1
std::cout << foobar.b << std::endl; // 2
...
But let's assume you already considered that and you actually do need to use list initialization. The answer is actually on that page you mentioned, let's expand on it.
When you want to write something like this with a custom class...
TestClass foobar = { 1, 2 };
It requires some manual work first. There's no magic that will automatically assign the 0th index to your first member and the 1st index to your second member.
The compiler requires an assignment operator or constructor that accepts an std::initializer_list:
/**
* TestClass.hpp
*/
class TestClass
{
public:
int a;
int b;
TestClass(std::initializer_list<int> list);
};
/**
* TestClass.cpp
*/
TestClass::TestClass(std::initializer_list<int> list)
{
if (list.size() != 2) {
// Throw an error or set some defaults
}
int i = 0;
for (int value : list) {
if (i == 0) {
this->a = value;
} else {
this->b = value;
}
i++;
}
}
This will do what you're expecting it to do. But that constructor is pretty funky, isn't it? We have to do that weird for
loop because std::initializer_list
doesn't offer indexed access to its values (In other words, you can't do list[0]
or list[1]
).
You can make this easier to read by accepting a std::vector
(or another kind of container like std::array
, std::list
, so on) in the constructor.
This works because an std::initializer_list
is accepted as a constructor in those containers, and an implicit conversion can be performed:
/**
* TestClass.hpp
*/
class TestClass
{
int a;
int b;
TestClass(std::vector<int> values);
};
/**
* TestClass.cpp
*/
TestClass::TestClass(std::vector<int> values)
{
if (values.size() != 2) {
// Throw an error or set some defaults
}
this->a = values[0];
this->b = values[1];
}