public bool default value?

Hi guys,

can you tell me what would happen, if I created an instance of a class without initializing a boolean class variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class tracer {
 private:
  double x; // x-coordinate
  double y; // y-coordinate
  double theta; // the angle of the velocity
  int nx;
  int ny;
 public:
  bool engaged;
  tracer();
  tracer(double ix, double iy, double ivangle);

}


Now suppose the self-defined constructor does not do anything to "engaged" and I create my object with this constructor: What value would "engaged" hold?
What would happen, if it was declared as "private"?

Regards!
Last edited on
private/public does not affect initialization.

Your engaged variable will contain a garbage value if used before having its value set.

https://arne-mertz.de/2015/08/new-c-features-default-initializers-for-member-variables/
If class members are neither mentioned in a constructor’s member initializer list nor have a brace-or-equal-initializer, then they get default-initialized. That means, that for class types the default constructor is called, but for any other types like enums or built in types like int, double, pointers, no initialization happens at all.

This applies for each element of array, and, as a corollary, it applies for plain old data classes as well, as their default constructor in turn default-initializes all of their members. No initialization means your member variables possibly contain garbage values.
Last edited on
> What value would "engaged" hold?

Examining the (uninitialised) value of the variable would engender undefined behaviour.
Note that it is uninitialised only if there has been no zero-initialisation.
https://en.cppreference.com/w/cpp/language/zero_initialization

Using a bool value in ways described by this document as “undefined”, such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false. http://eel.is/c++draft/basic.fundamental#footnote-45
Thank you.

So I should always make sure "engaged" is initialized correctly either at the construction of the object, or at least before I use it for the first time.
You should always make sure "all variables" are properly initialized prior to trying to use them.
Topic archived. No new replies allowed.