Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 222
J.Roe Avatar asked Dec 05 '22 11:12

J.Roe


1 Answers

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

like image 114
Ryan Haining Avatar answered Feb 16 '23 03:02

Ryan Haining