-1

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?

Galaxy
  • 2,363
  • 2
  • 25
  • 59

2 Answers2

0

It is just a default value as void foo(int i = 42);, there are no recursion.

foo(); is equivalent to foo(42);.

In the same way, with Simple(T value = T());

Simple<int> s{}; would be equivalent to Simple<int> s{0}; and Simple<std::string> s{}; would be equivalent to Simple<std::string> s{std::string{}}; (empty string).

T() would call the default constructor of given T (int and std::string in my examples).

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Can you clarify the last sentence? Why would these two expressions be equivalent? What would be the result if a different data type would be used? – Galaxy Oct 09 '18 at 23:02
0

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().

Seshadri VS
  • 550
  • 1
  • 6
  • 24