Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I list-initialize my own class?

Tags:

c++

c++11

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?

like image 293
Shiqing Shen Avatar asked Mar 13 '16 02:03

Shiqing Shen


People also ask

How do you initialize a class in C ++?

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.

What is initialize list in C++?

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.

Can you initialize values in a 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.

Does Java have initialization list?

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.


1 Answers

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;
}
like image 66
yuyoyuppe Avatar answered Oct 03 '22 05:10

yuyoyuppe