My web site - Chapter 8 Object-Based Programming 293 If a class
Chapter 8 Object-Based Programming 293 If a class does not define any constructors, the compiler provides a default (no-argument) constructor. This compiler-provided default constructor contains no code (i.e., the constructor has an empty body) and takes no parameters. The programmer also can provide a default constructor, as we demonstrated in class Time1(Fig. 8.1). Programmer-provided default constructors can have code in their bodies. Common Programming Error 8.3 If a class has constructors, but none of the public constructors is a default constructor, and a program attempts to call a no-argument constructor to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if there are no constructors for the class (in which case the compiler-provided default constructor is called) or if the class defines a public no-argument constructor. 8.6 Using Overloaded Constructors Like methods, constructors of a class can be overloaded. The Time1constructor in Fig. 8.1 initialized hour, minuteand secondto 0(i.e., 12 midnight in universal time) via a call to the class SetTimemethod. However, class Time2(Fig. 8.4) overloads the constructor to provide a variety of ways to initialize Time2 objects. Each constructor calls Time2 method SetTime, which ensures that the object begins in a consistent state by setting outof- range values to zero. C# invokes the appropriate constructor by matching the number, types and order of the arguments specified in the constructor call with the number, types and order of the parameters specified in each constructor definition. 1 // Fig. 8.4: Time2.cs 2 // Class Time2 provides overloaded constructors. 3 4 using System; 5 6 // Time2 class definition 7 public class Time2 8 { 9 private int hour; // 0-23 10 private int minute; // 0-59 11 private int second; // 0-59 12 13 // Time2 constructor initializes instance variables to 14 // zero to set default time to midnight 15 public Time2() 16 { 17 SetTime( 0, 0, 0 ); 18 } 19 20 // Time2 constructor: hour supplied, minute and second 21 // defaulted to 0 22 public Time2( int hour ) 23 { 24 SetTime( hour, 0, 0 ); 25 } Fig. 8.4 Fig. 8.Fig.Fi 8.4g. 8.44Overloaded constructors provide flexible object-initialization options. (Part Fig. 8. 1 of 2.)
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.