Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...