Initializer lists vs initializing in function

Mar 7, 2013 at 11:53pm
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;
}
Mar 7, 2013 at 11:54pm
#1 Should be your first choice, even in C++98.

#2 can only be slower than 1.
Mar 8, 2013 at 12:04am
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 Mar 8, 2013 at 12:06am
Mar 8, 2013 at 12:13am
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.
Mar 8, 2013 at 12:17am
Thanks a lot man!
Topic archived. No new replies allowed.