The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Member functions Initialize Or Construct? | ||
Initialize Or Construct?
Earlier we declared and initialized some Time structures using squiggly-braces: Time currentTime = { 9, 14, 30.0 };Time breadTime = { 3, 35, 0.0 }; Now, using constructors, we have a different way to declare and initialize: Time time (seconds);
If you define a constructor for a structure, then you have to use the constructor to initialize all new structures of that type. The alternate syntax using squiggly-braces is no longer allowed. Fortunately, it is legal to overload constructors in the same way we overloaded functions. In other words, there can be more than one constructor with the same "name," as long as they take different parameters. Then, when we initialize a new object the compiler will try to find a constructor that takes the appropriate parameters. For example, it is common to have a constructor that takes one parameter for each instance variable, and that assigns the values of the parameters to the instance variables: Time::Time (int h, int m, double s){ hour = h; minute = m; second = s; } To invoke this constructor, we use the same funny syntax as before, except that the arguments have to be two integers and a double: Time currentTime (9, 14, 30.0);
|
||
Home Member functions Initialize Or Construct? |