Consider the following example:
class Complex
{
float r, i;
};
main()
{
Complex x;
Complex∗ px = new Complex;
delete px;
}
According to my lecture notes. Operations in memory follow the following order:
- static/dynamic allocation of x/px
- initialization of members (done by the compiler)
- constructor call
- destructor call
I am confused about this. How come Initialization of data members is done before the constructor call?Isn't the job/purpose of the construtor to initialize members? To my understanding initializing means setting the values of the members, which is what we do in a constructor, right?(provided we implemented it, I am not sure what an empty constructor does I guess it does nothing so that members that are not static, global or dynamically-allocated keep their junk values) It seems to me that step 2 and step 3 are the same or at least that step 2 is contained in step 3, if the constructor does extra stuff.
I know that static, global and dynamically-allocated variables are default-initialized to 0, but in any other case, like primitive data types, there is no default-initialization, that is, they get whatever junk is in memory. So, in the example it seems like _r and _i of object x are left uninitialized, that is with junk values. While the object pointed by px is initialized to 0, since it's been dynamically-allocated
Isn't dynamic allocation supposed to happen at runtime? Then how can 1 happen after 2, provided that 2 is done by the compiler? So which of those steps are actually done by the compiler and which are not?
Can someone clear these points up?