Initializer lists vs initializing in function

I am just curious as to what is more "modern" IE C++11 common coding practices

What would be more appropriate

Node::Node(void):m_Data(0), m_Pnext(NULL), m_Pprev(NULL) {}

or

1
2
3
4
5
6
7
Node::Node()
{
    m_Pnext = NULL;
    m_Pprev = NULL;
    m_Data = 0;
}
#1 Should be your first choice, even in C++98.

#2 can only be slower than 1.
Thanks for the prompt reply!

so should I always go for #1 when I am just initializing stuff in a function/constructor even if its like 10 things that need to be initialized?

Also, if it is a short list of things such as I posted above, should I do it in the header or always put it in the cpp?
Last edited on
Yes, you should always construct the items directly whenever possible. If you don't put anything in the initializer list, it will be default constructed, so #2 would be:

1
2
3
4
5
6
Node::Node() : m_Pnext(), m_Pprev(), m_Data()
{
    m_Pnext = NULL;
    m_Pprev = NULL;
    m_Data = 0;
}


For basic types like int it may not do anything but for some other types calling the default constructor then assigning to it may be much slower.

If it's short, you can put it in the header if you want. I don't remember if constructors can be inlined or not.
Thanks a lot man!
Topic archived. No new replies allowed.