11.8. 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);

These two functions represent different programming styles, and different points in the history of C++. Maybe for that reason, the C++ compiler requires that you use one or the other, and not both in the same program.

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);

In the active code below, you can experiment passing values into the two different constructors that we have defined on this page and the previous page.

Implement two constructors for the Dog structure. One should be a default constructor, the other should take arguments. The weight needs to be converted from pounds to kilograms in the second constructor (for reference, 1 kilogram is approximately 2.2 pounds).

You have attempted of activities on this page