Home > OS >  How are we allowed to use a name of a data member in the constructor when the data member is defined
How are we allowed to use a name of a data member in the constructor when the data member is defined

Time:04-28

I am learning about classes in C . I asked a question before but it was closed as the duplicate of this and this while in reality neither of those duplicates answer my question. This is because i am looking for how it is formally allowed by the standard. Those dupes does not talk about how the C standard allow this usage.

So, i am trying to understand how the below example works according to the C standard:

struct Custom
{
    Custom(int j): i(j) //i is defined later even then we're able to used `i` here. How?
    {
        
    }
    
    private:
       int i = 0;
};

As seen in my example above, the data member i is defined at a leter point and even then we're able to use that name i in the constructor initializer list. My question is which clause(s) from the standard allows this usage? I mean normally when lookup happens it searches for names in the upward direction. But here it looks like the lookup happens also happens in the downward direction. So which cluase(s) apply here.

CodePudding user response:

This is because the body of a member function is a complete-class context and the constructor initializer is itself part of the member function's body as mentioned in the quoted statements below:

From class.mem.general#6:

6. A complete-class context of a class is a:

  • function body ([dcl.fct.def.general]),

  • default argument,

  • noexcept-specifier ([except.spec]), or

  • default member initializer

within the member-specification of the class.

The above means that a function body is a complete-class context of a class.

And from dcl.fct.def.general:

function-definition:
    [...] function-body

function-body:
    ctor-initializer_opt compound-statement

The above means that the ctor-initializer is part of the function body.


Combining the above two results together, we conclude that the ctor initializer i(j) is a complete-class context of the class Custom and hence the usage of i here is allowed here.

  • Related