Lesson 7 | Using a constructor |
Objective | Use a constructor to create an object. |
Constructor Object Declaration
We can declare objects of type mod_int
by using the mod_int
constructor. Here are two examples:
mod_int a(0); // a.v = 0;
mod_int b(61); // b.v = 1;
We could not, however, declare an object of type mod_int
without providing a parameter. The statement:
mod_int a;
would be incorrect.
Since the
mod_int
class has only the one constructor of argument list
int
,
a
mod_int
declaration must have an integral expression passed as an initializing value.
Note that by not allowing a
mod_int
object to be declared without an initializing expression, we prevent runtime errors due to uninitialized objects.
Using the
mod_int
type, we can write code to convert seconds into minutes and seconds.
See the
constructor example
Some Classes Cannot Rely on the Synthesized Default Constructor
Only fairly simple classes can rely on the synthesized default constructor.
The most common reason that a class must define its own default constructor is that the compiler generates the default for us only if we do not define any other constructors for the class. If we define any constructors, the class will not have a default constructor unless we define that constructor ourselves. The basis for this rule is that if a class requires control to initialize an object in one case, then the class is likely to require control in all cases.
The compiler generates a default constructor automatically only if a class declares no constructors.
A second reason to define the default constructor is that for some classes, the synthesized default constructor does the wrong thing. Remember that objects of builtin or compound type (such as arrays and pointers) that are defined inside a block have undefined value when they are default initialized
The same rule applies to members of built-in type that are default initialized. Therefore, classes that have members of built-in or compound type should ordinarily either initialize those members inside the class or define their own version of the default constructor.
Otherwise, users could create objects with members that have undefined value.
Warning: Classes that have members of built-in or compound type usually should rely on the synthesized default constructor only if all such members have in-class initializers.
A third reason that some classes must define their own default constructor is that sometimes the compiler is unable to synthesize one.
For example, if a class has a member that has a class type, and that class does not have a default constructor, then the compiler cannot initialize that member. For such classes, we must define our own version of the default constructor. Otherwise, the class will not have a usable default constructor.
We will see additional circumstances that prevent the compiler from generating an appropriate default constructor