Search code examples
c++c++11default-constructor

Why I get this warning? "Member 'x' was not initialized in this constructor"


given the following code:

class Class {
    int x;
public:
    Class() = default;
};  

I get the following warning:

Member 'x' was not initialized in this constructor

What is the reason of this warning?


Solution

  • x is an int and its default initialization leaves it with an indeterminate value. The simplest, most uniform fix is to value-initialize it in its declaration.

    class Class {
        int x{}; // added {}, x will be 0
      public:
        Class() = default;
    };
    

    You could also do int x = 5; or int x{5}; to provide a default value