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
  • 195,986
  • 40
  • 382
  • 396
xmllmx
  • 37,882
  • 21
  • 139
  • 300

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,103
  • 3
  • 45
  • 71
juanchopanza
  • 216,937
  • 30
  • 383
  • 461
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
  • 54,116
  • 13
  • 115
  • 176
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,057
  • 6
  • 63
  • 89
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
  • 145,940
  • 13
  • 211
  • 371
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
  • 161,154
  • 30
  • 262
  • 319