I want my own class can be list-initialized like vector:
myClass a = {1, 2, 3};
How can I do that using C++11 capabilities?
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
As for why Java does not have initializer lists like C++, I would assume that the reason is because all fields are already initialized by default in Java and also because Java uses the super keyword to call the super(or base in C++ lingo)-class constructor.
C++11 has a notion of initializer lists. To use it, add a constructor which accepts a single argument of type std::initializer_list<T>
. Example:
#include <vector>
#include <initializer_list>
#include <iostream>
struct S
{
std::vector<int> v_;
S(std::initializer_list<int> l)
: v_(l)
{
std::cout << "constructed with initializer list of length " << l.size();
}
};
int main()
{
S s = { 1, 2, 3 };
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With