Setting values inside the class versus setting them via constructors

Hello Everyone, I was wondering why there seems to be a preference to setting values in constructors rather than inside the class itself. Both work equally well in my experience.


1
2
3
4
5
  template <class T>
  struct Node{
      Node * pNext = NULL;
      T pData;
  }



Why does it seem more preferable to do the code below?

1
2
3
4
5
6
7
8
9
10
11
  template <class T>
  struct Node {
      Node * pNext;
      T pData;
  }

  template <class T>
  Node<T>::Node()
  {
      pNext = NULL;
  }



Both set pNext to NULL. So what's the problem? Or was I mistaken.



As a weird, less important, bonus question, I'm also wondering why constructors don't need to include the template class in the title.

F.E.

Why do this?
1
2
3
4
5
  template <class T>
  Node<T>::Node()
  {
      pNext = NULL;
  }



Rather than this?

1
2
3
4
5
  template <class T>
  Node<T>::Node<T>() // DIFFERENCE IS ON THIS LINE
  {
      pNext = NULL;
  }
first: it's because you can't initialize non-static members in the class itself before c++11, you could only do it in the constructor.
Nowadays yes, you could write it like this if you want but it would only work with c++11 or newer so your class can't be used in older projects.
If you don't care just go on, do it, I hope C++11 won't be experimental some day.
If you want your class to support all c++ standards you should probably make a constructor.

second: it's because the Method Node() is not a template method.
it's your class that is a template so every Node<T> has a method named Node()

you could write it like yours if you did it like this but that would make little sense and it would probably not compile:
1
2
3
4
5
6
7
8
template <typename T>
class Node {
public:
    template <>
    Node<T>();
};
template<typename T>
Node<T>::Node<T>() {}
Topic archived. No new replies allowed.