This code has a templated class. The default constructor appears to call itself recursively. How can it do that? I don't understand this code. Maybe if I would be given an example without templates, just POD types, things would be clearer. I haven't encountered this construct before in C++ programming. I think that I don't understand both the constructor and the templates.
template <typename T>
class Simple {
public:
Simple(T value = T()); // What's this?
T value();
void set_value(T value);
private:
T value_;
};
template<typename T>
Simple<T>::Simple(T value) {
value_ = value;
}
template<typename T>
T Simple<T>::value() {
return value_;
}
template<typename T>
void Simple<T>::set_value(T value) {
value_ = value;
}
My question is:
What does T value = T()
do?
Class Simple has a variable value
of type T
(Templated).
The constructor which you are pointing is a default constructor. When no parameter is supplied while creating Simple
object. Then default constructor will instantiate the value object to the default constructor of T.
Either , Simple(T value = T())
is a default constructor which is instantiating value to default constructor of typed element.
Example :- if T is String.
Simple (String value = String())
so value is now initialized to default of String().