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;
};
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is a member initializer list, and is part of the constructor’s implementation.
The constructor’s signature is:
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.