Could you help me understand why int num(5) work? This syntax looks
like initializing an object
For the basic case (where the programmer explicitly types in a line of code like int num(5);
or int num = 5;
, having two different syntaxes that both do the same thing seems unnecessary, and it is.
However, once you get into templates, you'll find cases where you want to write a template that can work with both user-defined classes and with the built-in types. For example, here is a template I wrote the other day to save (and later restore) the state of an arbitrary value:
template<class T> class SaveGuard
{
public:
SaveGuard(T & saveMe) : _saveMe(saveMe), _tempHolder(saveMe) {/* empty */} // save the current value
~SaveGuard() {_saveMe = _tempHolder;} // restore the saved value
private:
T & _saveMe;
T _tempHolder;
};
Note that in this case, the _tempHolder(saveMe)
clause is syntactically the same as the int(5)
syntax, and since the int(5)
syntax is supported, I can declare a SaveGuard<int> guard(blah);
in my program and it will work as expected. Alternatively I can declare a SaveGuard<MyClassType> guard(blah);
and the template will work for that as well, using the copy-constructor of the MyClassType
class.
What is the difference between the two in terms of speed and stuff
that goes behind
There's no difference in speed in your example; the compiler will generate the same assembly code for either syntax.