A member with an in-class initializer must be const

a member with an in-class initializer must be const

This error or requirement arises when you try to initialize a member variable of a class using an in-class initializer, but the member variable itself is not declared as ‘const’.

In-class initializers are used to provide default values to member variables directly at the point of declaration. This means that when an object of the class is created, the member variable is automatically initialized with the provided value.

However, if you want to use an in-class initializer, you need to ensure that the member variable is declared as ‘const’. This is because in-class initializers are only allowed for ‘const’ members to guarantee that their values cannot be modified after initialization.

Here’s an example that illustrates this scenario:


    class Example {
      const int member = 10; // OK, 'member' is declared as const and initialized with 10

      int nonConstMember = 20; // Error! 'nonConstMember' is not declared as const

      // ...
    };
  

In the example above, ‘member’ is declared as ‘const’ and initialized with the value 10. This is allowed because ‘member’ cannot be modified after initialization.

On the other hand, ‘nonConstMember’ is not declared as ‘const’, so trying to initialize it with an in-class initializer results in an error.

To resolve this error, you have two options:

  1. Remove the in-class initializer and initialize the member variable in the class constructor instead. This way, you can initialize both ‘const’ and non-const members.

    
            class Example {
              const int member; // Declaration without initializer
    
              int nonConstMember;
    
              Example() : member(10), nonConstMember(20) {
                // ...
              }
            };
          
  2. Declare the member variable as ‘const’ if you want to use an in-class initializer. This ensures that the value of the member variable cannot be modified after initialization.

    
            class Example {
              const int member = 10; // Declaration with in-class initializer
    
              // ...
            };
          

Related Post

Leave a comment