Question: I am having trouble understanding ctors. In the hangman program most of the constructors have them. I think the ctor is supposed to execute before the instance of the class is created. Is this correct?
Answer: No, that is not correct. Things happen in this order:
- Space on the run-time stack is allocated for the core portion of the new object.
-- This includes space for the core portion of all data components of the class.
-- If the object is of a derived class, it also includes space for all base classes.
- If the object is of a derived class, one of the constructors for the base-class portion of the object is run to INITIALIZE the base portion of the object (it has already been allocated).
-- If there is no ctor initializer, the zero-parameter constructor for the base class is run.
-- If there is a ctor initializer for the base class, it is used instead of the zero-parameter constructor. This kind of ctor has the form BaseClassName( parameter list ) The parameter list must match one of the constructor prototypes in the base class.
- Next, the remaining ctor initializers are used to initialize the data members of the object. These ctors have the form: member_name( initial_value )
- Finally, the code portion of the object constructor is run. This code do anything. It is usually used to allocate the extension portion of the object, set various fields to 0, and connect pointers into a legal and meaningful data structure.
Question: What would be the benefit of this way of doing things? Answer:
- All stack space is allocated first. There is no other way that makes sense.
- Clearly, some stable and predictable order must be uniformly used to initialize the members of an object and construct its extensions. It makes sense to start at the first data member and progress downward.
- The members of the base class must be initialized first, since other parts of the object might refer to them. To do this, we must have some way to select one of the base-class constructors and pass parameters to it. This is what the first kind of ctor is for.
- The rules for assignment and initialization are different in C (and C++). For example, you can and must initialize a const variable but you cannot assign a new value to it. The second kind of ctor initializer is necessary to provide initial values for const members of the class. It can also be used to initialize non-const members, but that job could also be done by an assignment in the body of the constructor function.