P. 1


|Views: 9|Likes:
Published by Jiz Satar

More info:

Published by: Jiz Satar on Dec 03, 2010
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





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


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.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->