Ctor initailzers and other related topics.
Objectives
Notes
Default parameter values
It is permissible to provide default values to a function parameter
It is done by
type paramID = value
It must be done from the last parameter to the first.
Trailing arguments
Parameters are filled in from the start
With any missing replaced by default parameters.
You place the values either in the function prototype or the implementation but not both.
I prefer the prototype as this is the "documentation" of the function.
If you provide defaults to all parameters of a constructor then this becomes the default constructor.
See
paramDemo.cpp
.
Ctor Initializers
These are needed
So we can call base class constructors with parameters.
Or any component constructors that are parameterized.
We wish to be efficient
Three ways to provide a value to class member data
Inside the constructor
In the class declaration (ie where the variables are declared)
In the constructor initialzer
In the class declaration
This is static, ie it is set for the class and can not be changed without recompiling.
It is the lowest default, ie used if the other two are not.
The constructor
This is dynamic in that it can be based on parameters or calculated at run time.
It is, however a copy operation, not an initialization
this possibly consumes more time.
And is not acceptable with the creating an object that does not have a default constructor.
The ctor initializer
This overrides from the definition
But will be overridden by the constructor body
These can be based on parameter values or other computations, so are dynamic
ctor-initializer format
Identifier(parameter list): member{value}, member{value}, ... { body}
Note: the members must be initialized in the order they are declared
Ctor-initializers support two additional class variable member types
Constant values, that can be initialzied at run time.
Reference member variables.
Reference member variables
I don't know if I like this or not, but remember, a reference points to memory.
This is fine if the memory is guaranteed to exist as long as the reference is in lifetime.
The reference as a class member makes this somewhat more challenging.
But the same would be true of a pointer member, so this is just a tool we need to be careful with.
A reference means we don't copy a large data structure, just point to it.
This wold be useful in a game, the game board is always a problem for me.
With both const members and reference members you need a copy constructor if you are going to copy.
And I don't think you can do an assignment operator to cover these fields, they will get the default value.
But I think it forces you to write one anyway.
Take a look at
ctorDemo.cpp