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.


Another function we wrote in Chapter 9 was makeTime:

Time makeTime (double secs) {
  Time time;
  time.hour = int (secs / 3600.0);
  secs -= time.hour * 3600.0;
  time.minute = int (secs / 60.0);
  secs -= time.minute * 60.0;
  time.second = secs;
  return time;

Of course, for every new type, we need to be able to create new objects. In fact, functions like makeTime are so common that there is a special function syntax for them. These functions are called constructors and the syntax looks like this:

Time::Time (double secs) {
  hour = int (secs / 3600.0);
  secs -= hour * 3600.0;
  minute = int (secs / 60.0);
  secs -= minute * 60.0;
  second = secs;

First, notice that the constructor has the same name as the class, and no return type. The arguments haven't changed, though.

Second, notice that we don't have to create a new time object, and we don't have to return anything. Both of these steps are handled automatically. We can refer to the new object---the one we are constructing---using the keyword this, or implicitly as shown here. When we write values to hour, minute and second, the compiler knows we are referring to the instance variables of the new object.

To invoke the constructor, you use syntax that is a cross between a variable declaration and a function call:

  Time time (seconds);

This statement declares that the variable time has type Time, and it invokes the constructor we just wrote, passing the value of seconds as an argument. The system allocates space for the new object and the constructor initializes its instance variables. The result is assigned to the variable time.

Last Update: 2005-11-21