c++11in-class-initialization

What exactly is the in-class-initializer?


I've read many text mentioned the in-class-initializer and I've searched many question on stackoverflow, However I didn't found any precise explanation on what is the in-class-initializer. And as far as I understood the variable of build-in type declared outside any function will be default initialized by the compiler, does the in-class-initilizer doing the same action for a declared variable?


Solution

  • Here is a simple example for in-class initialization. It's useful for less typing, especially when more than one constructor signatures are available. It's recommend in the core guidelines, too.

    class Foo {
      public:
        Foo() = default; // No need to initialize data members in the initializer list.
        Foo(bool) { /* Do stuff here. */ } // Again, data member already have values. 
    
      private:
        int bar = 42; 
        //      ^^^^ in-class initialization
        int baz{};
        //     ^^ same, but requests zero initialization
    };
    

    As the data members are explicitly initialized, the second part of your questions doesn't really apply to to in-class initialization.