Unfamiliar with Timer syntax

Can someone explain this syntax to me:

Timer timer(1000, print_every_second);

It looks like both a function call, but it’s also declaring a variable timer?

Thanks!

Looks like a library call to me, in which you initialize them with the set values.

Correct. This is declaring a class instance variable of type Timer, whose variable name is timer (lower-case), and whose constructor parameters are (1000, print_event_second).

This is a handy syntax to use for global objects because the memory used by the Timer object is a pre-allocated at compile time, so you don’t have to check for errors like when you allocate a new object on the heap with new Timer(). Also, you reference its member functions with “timer.” instead of “timer->” which is easier to type.

Is there a name for this type of construct?

@jonlorusso, it is called class instantiation. This takes a class construct and builds a real object out of it.

@peekay123 Yes, but is there a name for this particular syntactic construct. I am referring specifically to the compile-time form @rikkas7 mentioned above (as opposed to “normal” constructors), where the variable name and constructor are one:

Timer arbitrary(1000, print_every_second);

I believe it’s the functional form of class declaration. The other ways are default constructor form (no parentheses) and uniform initialization (uses curly brackets).
http://www.cplusplus.com/doc/tutorial/classes/

1 Like

Thanks! That was exactly what I was looking for!

1 Like