I did not work with C++ for many years, and now i wrote c++ project with test.
When i started to debug i find strange thing that variables are not initializing with zero by default. For example when i watch to the my class uninitialized variable (unsigned int), i see its value 3452816845 insted of expected zeo... Thats cause errors in unit-tests. I use such initializattyion:
TEST_METHOD(TestPlus)
{
Entity* entity = new Entity();
entity->mCreateOperator(entity->Plus);
entity->SetContactValue(1);
entity->SetContactValue(2);
entity->mProcessLast();
Assert::IsTrue(entity->GetContactValue((1+2));
}
I have default constructor for Entity class :
Entity::Entity(void) {/*some internal array initialization*/}
I considered that when i using new keyword all class variables will be initialized with 0 by C++ runtime..
Did i miss somethisg?
The data members of your class are left uninitialized specifically because you explicitly asked the compiler to leave them uninitialized. You did this by writing a default constructor that does nothing to initialize them
Entity::Entity(void) { /*some internal array initialization*/ }
If your class had no user-defined constructor, then this syntax
Entity* entity = new Entity();
would trigger so called value-initialization of the new object, which would indeed set all immediate scalar data members of Entity
to zero.
However, the very moment you wrote your own default constructor Entity::Entity()
you basically told the compiler that you want to suppress value-initialization for Entity
class and that you want to initialize such members manually. So now you have to to exactly that: manually initialize all immediate scalar data members of Entity
. Since you did not do that in your constructor, these members were left uninitialized.
Actually the value 3452816845
(0xCDCDCDCD) is a special fill-pattern used by Microsoft's runtime to IDENTIFY uninitialized variables. The compiler does this so that you can detect when you have forgotten to initialize a variable, and this value was picked as a "good" value because it isn't a valid address and is a large number as unsigned, and a "large" negative number in the signed range, so it's typically easy to notice that something is wrong when your code uses one of these values - it's nearly always WAY outside the range you expect it to be in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With