I need a default constructor with no argument. How can I initialize attribute a
which is of unknown type to me.
template <typename Type>
class Foo
{
public:
Foo() : a(), b(0) {} <---- Here is the confusion
private:
Type a;
int b;
};
Edit : Answer has been given in comments below, but there is still something I don't understand. If I have :
typedef enum {AB, CD} EnumType
template <typename Type>
class Foo
{
public:
Foo() {} // <---- "Member 'b' was no initialized in this constructor"
private:
Type a;
EnumType b;
};
my compiler gives me this warning : Member 'b' was no initialized in this constructor
. Why is it giving me this warning for b
which is an enum and not for a
?
How can I initialize attribute a which is of unknown type to me.
Your solution is correct. Per Paragraph 8.5/11 of the C++11 Standard:
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized. [...]
Then, Paragraph 8.5/8:
To value-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;
— if T is a (possibly cv-qualified) non-union class type without a user-provided or deleted default constructor, then the object is zero-initialized and, if T has a non-trivial default constructor, default-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized.
Finally,
Why is it giving me this warning for b which is an enum and not for a ?
That is probably because you specify a template argument for Type
which is a UDT (user-defined type) which can be default-constructed. If this is not the case, then I would expect the compiler to also warn you about a
not being initialized in the constructor. Notice, however, that the compiler is not required to issue any such warning.