What does a colon following a C++ constructor name do?

spencewah picture spencewah · Aug 13, 2009 · Viewed 52k times · Source

What does the colon operator (":") do in this constructor? Is it equivalent to MyClass(m_classID = -1, m_userdata = 0);?

class MyClass {
public:

    MyClass() : m_classID(-1), m_userdata(0) { 
    }

    int m_classID;
    void *m_userdata;
};

Answer

Daniel Daranas picture Daniel Daranas · Aug 13, 2009

This is an initialization list, and is part of the constructor's implementation.

The constructor's signature is:

MyClass();

This means that the constructor can be called with no parameters. This makes it a default constructor, i.e., one which will be called by default when you write MyClass someObject;.

The part : m_classID(-1), m_userdata(0) is called initialization list. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice, instead of leaving them as undefined.

After executing the initialization list, the constructor body (which happens to be empty in your example) is executed. Inside it you could do more assignments, but once you have entered it all the fields have already been initialized - either to random, unspecified values, or to the ones you chose in your initialization list. This means the assignments you do in the constructor body will not be initializations, but changes of values.