0

If I have a class defined and one of the data members is a double (for example), what is the value of that double when an object of that class is instantiated? Is it zero, or do I need to explicitly set it to zero?

TIA Fred Emmerich

FWE1
  • 11
  • 2
  • 3
    As a rule of thumb in C++ always explicitly set it. There are many cases where it will remain uninitialized if you don't. Only a few specific cases where it would be initialized to a guaranteed 0 if you don't explicitly do anything - so if you don't know which those are, then the it's easy to initialize it to the value you want, just to be sure. – TheUndeadFish Sep 29 '22 at 21:17
  • 1
    C++ doesn't automatically initialize variables because there is a general policy that c++ doesn't add things that you don't use for performance. This differs from most other languages. – doug Sep 29 '22 at 21:34

2 Answers2

2

The variable is uninitialized and can be anything. Using it is undefined behavior. You would have to initialize it yourself, see also https://en.cppreference.com/book/uninitialized

EDIT: The answers to the following related questions are a good read:

joergbrech
  • 2,056
  • 1
  • 5
  • 17
0

Generally, the variable is uninitialized, except for the variable being static. In this case, the variable is zero initialized, when there is no constant initialization.

Zero-initialization is performed [...] For every named variable with static or thread-local (since C++11) storage duration that is not subject to constant initialization, before any other initialization.

https://en.cppreference.com/w/cpp/language/zero_initialization

Nevertheless, I think initializing variables is good practice.

Robin
  • 11
  • 6
  • Is there any difference between a variable that is done in normal code vs. a variable that is a data member of a class? – FWE1 Sep 30 '22 at 22:04