Home > Mobile >  Is member initializer list considered part of the body of a constructor or it it considered part of
Is member initializer list considered part of the body of a constructor or it it considered part of

Time:04-25

I am learning about member initializer lists in C . So consider the following example:

struct Person
{
    public:
        Person(int pAge): age(pAge)
//                        ^^^^^^^^^ is this member initializer formally part of the constructor body? 
        {
        }
    private:
        int age = 0;
};

My first question is that is the member initializer age(pAge) formally part of the constructor's body. I mean i've read that a function's body starts from the opening { and end at the closing }. To my current understanding, there are four things involved here:

  1. Ctor definition: This includes the whole
//this whole thing is ctor definition
Person(int pAge): age(pAge)
        {
        }
  1. Member initializer: This is the age(pAge) part.

  2. Ctor declaration: This is the Person(int pAge) part.

  3. Ctor's body: This is the region between the opening { and the closing }.

My second question is that is the above given description correct? If not then what should be the correct meaning of those four terms according to the C standard: Ctor definition, Member initializer, Ctor declaration and Ctor's body.

PS: I've read this post which doesn't answer my question. In particular, i am looking for the clauses from the C standard that might help answer the two questions asked in my question.

CodePudding user response:

is the member initializer age(pAge) formally part of the constructor's body?

Yes, as from Constructors and member initializer lists:

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list, whose syntax is the colon character :, followed by the comma-separated list of one or more member-initializers,...


is the above given description correct?

In the 4th point of your second question, the constructor's body also include the member initializer list as quoted above.

CodePudding user response:

In your example, age(pAge) is part of the implementation, not the declaration. If you changed it to age(pAge 1), callers wouldn’t change. The implementation of the constructor will call the baseclass constructor, then default constructors or constructors like age(pAge), can’t remember the order, then the compiled source code of the constructor. I’d consider the syntax a bit strange.

  • Related