Ru-Brd |
For fundamental types such as int , double , or pointer types, there is no default constructor that initializes them with a useful default value. Instead, any noninitialized local variable has an undefined value: void foo() { int x; // x has undefined value int* ptr; // ptr points to somewhere (instead of nowhere) } Now if you write templates and want to have variables of a template type initialized by a default value, you have the problem that a simple definition doesn't do this for built-in types: template <typename T> void foo() { T x; // x has undefined value if T is built-in type } For this reason, it is possible to call explicitly a default constructor for built-in types that initializes them with zero (or false for bool ). That is, int() yields zero. As a consequence you can ensure proper default initialization even for built-in types by writing the following: template <typename T> void foo() { T x = T(); // x is zero (or false )if T is a built-in type } To make sure that a member of a class template, for which the type is parameterized, gets initialized, you have to define a default constructor that uses an initializer list to initialize the member: template <typename T> class MyClass { private: T x; public: MyClass() : x() { // ensures that x is initialized even for built-in types } }; |
Ru-Brd |