Updates: The reason I was getting true is because anything that is other than 0 would be considered true which obviously makes sense to how unlikely it would have been for me to get false when uninitialized.
I have read a post similar to my question on StackOverflow, it talked about that it is good practise to initialize all member variables, which I agree with. Post: Boolean variables aren't always false by default?
This post is a bit old (9 years ago) so I just think maybe somethings might have been changed in the new C++ versions, I am currently using C++17. I also have one slight different question from the ones talked about in the post.
I am aware that if a variable is uninitialized it may contain some "garbage data" or as one of the answers in the post said (which I think that is what they meant but I'm not 100% sure), "if not explicitly initialized -- will contain an arbitrary value.".
I have tried testing that, and the results showed that when I didn't initialize my variables, they contained random numbers (for int, double). I also tested std::string but they are set to "" by default from what I saw.
Anyways, now when I tried for the built in type bool
I would always get true (after class is constructed, but again that boolean value never initialized, I would go into debug and see that the value would be true), what I am confused is that no matter how many times I tried to test if that was just a random value out of true and false, and if sometimes it would be false, it was always set to true. If uninitialized shouldn't the value be "random" kind of? Why did it always set to true (again when a member variable of my class which wasn't initialized on construction).
Solutions I tried: Obviously one is just to initialize on construction, but I thought of another one...
What if on construction I wanted it to be true and not false but when it hasn't been constructed to be set to false then that way when I have a vector of pointers to my object I can check that I am not reading uninitialized objects when following the pointer by checking whether that boolean is set to true (if initialized) or false otherwise. I wouldn't be able to use method 1 which was to initialize on construction to false, also because if we are reversing the behaviour I can't rely on what that uninitialized boolean member variable would be as I mentioned in the above paragraphs I am unsure what behaviour that has due to the results I had been getting. I did the following and it worked...
class Testing{
private:
bool condition{false} // Initalize it here which kind of makes me confused but it works
public:
Testing() : condition{true} {} // Constructor setting the condition value to true
};
Could someone explain if it is wrong to do this, personally I have never seen someone do this but I tried it and no errors were given.