What does a colon following a C++ constructor name do? [duplicate]

This is a member initializer 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 member initializer list. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice.

After executing the member initializer 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.

Leave a Comment