Search code examples
c++initialization

Direct Initialization of member in class definition


Why can't we use direct initialization within a class definition? For example, we can use a int z = 5; statement, but can't use int y(10); within the class definition below.

class Myclass {      
  int y(); // "error: expected ',' or '...' before numeric constant
  int z=5;
};

Solution

  • Per member initialization:

    Non-static data members may be initialized in one of two ways:

    1. In the member initializer list of the constructor.
    struct S
    {
        int n;
        std::string s;
        S() : n(7) {} // direct-initializes n, default-initializes s
    };
    
    1. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.
    struct S
    {
        int n = 7;
        std::string s{'a', 'b', 'c'};
        S() {} // default member initializer will copy-initialize n, list-initialize s
    };
    

    So, you can use curly braces instead of parenthesis:

    int y{10};

    This will invoke direct initialization in this case:

    T object { arg }; (2) (since C++11)

    Direct initialization is performed in the following situations:
    ...
    2) initialization of an object of non-class type with a single brace-enclosed initializer (note: for class types and other uses of braced-init-list, see list-initialization) (since C++11)