15

I run across a weird concept named "member initializer".

Here says:

C++11 added member initializers, expressions to be applied to members at class scope if a constructor did not initialize the member itself.

What is its definition?

Are there some examples to illustrate its usage?

Mat
  • 202,337
  • 40
  • 393
  • 406
xmllmx
  • 39,765
  • 26
  • 162
  • 323

5 Answers5

18

It probably refers to in-class member initializers. This allows you to initialize non-static data members at the point of declaration:

struct Foo
{
  explicit Foo(int i) : i(i) {} // x is initialized to 3.1416
  int i = 42;
  double x = 3.1416;
};

More on that in Bjarne Stroustrup's C++11 FAQ.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
7

You can now add initializers in the class which are shared for the constructors:

class A
{
   int i = 42;
   int j = 1764;

public:
   A() {} // i will be 42, j will be 1764
   A( int i ) : i(i) {} // j will be 1764
};

It avoids having to repeat initializers in the constructor which, for large classes, can be a real win.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
1

C++11 allows non-static member initialization like this:

class C
{
   int a = 2; /* This was not possible in pre-C++11 */
   int b;
public:
   C(): b(5){}

};
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
1

Member initializers is referring to the extension of what initializers can be set up in the class definition. For example, you can use

struct foo
{
     std::string bar = "hello";
     std::string baz{"world"};
     foo() {}                              // sets bar to "hello" and baz to "world"
     foo(std::string const& b): bar(b) {}  // sets bar to b and baz to "world"
};

to have bar initialized to hello if the member initializer list doesn't give another value. Note that member initializers are not restricted to build-in types. You can also use uniform initialization syntax in the member initializer list.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

From here:-

Non-static Data Member Initializers are a rather straightforward new feature. In fact the GCC Bugzilla reveals novice C++ users often tried to use it in C++98, when the syntax was illegal! It must be said that the same feature is also available in Java, so adding it to C++ makes life easier for people using both languages.

 struct A
  {
    int m;
    A() : m(7) { }
  };

  struct B
  {
    int m = 7;   // non-static data member initializer
  };
thus the code:

  A a;
  B b;

  std::cout << a.m << '\n';
  std::cout << b.m << std::endl;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331