Search code examples
c++classtemplatesinitializationdefault-constructor

How to initialize a template object inside a class C++?


I want to create a template Node class like this

template <class T>
class Node {
public:
    Node() {
        val = T;
        // Does not work: new T, NULL, 0, ""
    }
    // ...
private:
    vector<Node<T> *> children;
    T val;
    Node<T> * parent = NULL;
}

The constructor is supposed to have no initial value as a parameter and no overloads are allowed. I could potentially not do anything in the constructor, but for example for integers, I want this base value to be 0, etc. Essentially, the problem I'm trying to avoid is to eliminate undefined behavior eg such values when using integers (the first one is root with no value set): -1021203834 1 2 11 12 21 22 1 11 12


Solution

  • Either you can write

    Node() : val() {}
    

    or

    Node() : val{} {}
    

    Or in the class definition to write

    T val {};