Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

C++ Member Initialization List

Please explain how to use member initialization lists. I have a class declared in a .h file and a .cpp file like this:

class Example
{
private:
    int m_top;
    const int m_size;
    ...
public:
    Example ( int size, int grow_by = 1 ) : m_size(5), m_top(-1);
    ...
    ~Example();
};

I'm initializing m_size on object creation because of const. How should I write the constructor? Should I repeat : m_size(5), m_top(-1), or I can omit this step?

Example::Example( int size, int grow_by)
{
... some code here
}

or

Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to clarify something that came up in some of the other answers...

There is no requirement that the initialization list be in either the source (.cpp) or header (.h) file. In fact, the compiler does not distinguish between the two types of files. The important distinction is between the contructor's declaration and it's definition. The initialization list goes with the definition, not the declaration.
Usually, the declaration is in a header file and the definition is in a source file, however, this is not a requirement of the language (i.e. it will compile). It is not unusual to provide constructor definitions inline in the class declaration when the constructor is empty or short. In that case an initialization list would go inside the class declaration, which would probably be in a header file.

MyClass.h

class MyClass
{
public:
    MyClass(int value) : m_value(value)
    {}
private:
    int m_value;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...