What does a colon following a C++ constructor name

2019-01-02 19:49发布

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;
};

9条回答
大哥的爱人
2楼-- · 2019-01-02 20:26

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 and m_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.

查看更多
流年柔荑漫光年
3楼-- · 2019-01-02 20:31

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 using MyClass m = MyClass(3, 4), which would result in m_classID being 3, and m_userdata being 4). If I were to pass no arguments to the MyClass constructor, it would result in an equivalent object being created to the version with the initialiser list.

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 20:38

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.

查看更多
登录 后发表回答