I am currently taking a c++ course and trying to get a deep understanding of the whole thing. I came up with some theories, it would be great if somebody could confirm them:
Every variable (local,global,staic,member and non-member) is guaranteed to have its ctor called before first use
The ctors of primitives like int are essentially no-ops, so we have explicitly assign a value, there is no default zero value.
the following classes are semantically the same (and should generate identical code)
class A
{
int n;
};
and
class A
{
int n;
public:
A() : n() {}
};
and
class A
{
int n;
public:
A() { n = int(); }
};
The variable n is in every case still uninitialized.
EDIT:
It seem that I absolutetly underestimated the complexity of this subject, most of my assumptions were wrong. Now Iam still trying to find out the basic rules of object initialisation.
I'm afraid you are wrong. When you say:
int n = int();
Then n (and all other POD types) will zero initialised.
Also, make sure that you are very clear in your mind about the difference between initialisation and assignment - this is quite important in C++:
int n = int(); // initialisation
n = 0; // assignment
You might find this interesting.
The difference between new Foo and new Foo() is that former will be uninitialized and the latter will be default initialized (to zero) when Foo is a POD type. So, when not using the form with the parens, the member "a" can contain garbage, but with the parens "a" will always be initialized to 0.
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