Juha said:
Pascal said:
"[p]rimitive type member
variable like int, float etc does not have any constructors
That's not true.
No, that's true.
C++ defines constructors for them because else it
would be very difficult to create many template functions/classes which
handle variables with default values.
No, non-class types in C++ have no constructors. That's how it is
defined by the official language specification.
Alternative sources might decide to follow a different terminological
approach, deviating from the official terminology for one reason or
another. For example, Stroustrup's TC++PL book is known to state that
scalar types have constructors (apparently, for the sake of simplicity).
This is completely valid:
int i = int();
The rhs basically creates a nameless int and calls its default
constructor (which initializes it to 0).
No (once again, in the official terminology).
The 'int()' expression is a functional-style cast to type 'int' with an
empty set of arguments. Such a case in C++ language produces a
default-initialized unnamed temporary object of type 'int'.
Default-initialization for type 'int' means zero-initialization. That's
it. Note, that nowhere in this description any constructors are mentioned.
Your description, however, is easy to prove wrong. If type 'int' had a
default constructor, the 'int i;' declaration for an automatic variable
would call that constructor and zero-initialize the variable. This
doesn't happen. The same can be said about objects created with 'new
int'. Of course, you can explain this as some kind of exception from the
general rule, but, once again, this will be a non-standard view of the
program behavior.
This is also completely valid:
void foo(int var);
foo(int());
This is the same thing as the previous example.
(It creates a nameless temporary of type int, constructs it with its
default constructor, and gives it as parameter to foo.)
It does create a nameless temporary, but no "default constructors" are
involved here. Once again, in C++ only class types can have constructors.
Why would anyone want to do that? Why not just do "int i = 0;" and
"foo(0);"? Well, the reasoning behind this becomes clearer with templates:
template<typename T>
void foo()
{
T var = T();
...
}
This will work even if T is of type int (or any other primitive type).
True. But the generic concept that is used here is called
_initialization_, not _construction_. What we observe here is that
different (almost all) types can be _initialized_ with '()'. The
semantics of that initializer is different for different types. And only
for class types it might result in a constructor call (not for all class
types, BTW).