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"?
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.
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
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.