This question already has an answer here:
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;
};
That is called the member initialization list. It is used to call the superclass constrctors, and give your member variables an initial value at the time they are created.
In this case, it is initializing
m_classID
to -1 andm_userData
to NULL.It is not quite equivalent to assigning in the body of the constructor, because the latter first creates the member variables, then assigns to them. With the initialization, the initial value is provided at the time of creation, so in the case of complex objects, it can be more efficient.
It denotes the beginning of an initialiser list, which is for initialising member variables of your object.
As to:
MyClass(m_classID = -1, m_userdata = 0);
That declares a constructor which can take arguments (so I could create a
MyClass
usingMyClass m = MyClass(3, 4)
, which would result inm_classID
being 3, andm_userdata
being 4). If I were to pass no arguments to theMyClass
constructor, it would result in an equivalent object being created to the version with the initialiser list.In this case: Yes, ist is equivalent because only primitive types are concerned.
If the members are classes (structs) then you should prefer the initialization list. This is because otherwise the objects are default constructed and then assigned.