Home > Enterprise >  Why the `this` pointer worked in constructor in C ?
Why the `this` pointer worked in constructor in C ?

Time:05-05

I know the this pointer will point to the object instance that currently in, but I don't know how to implement it.

And I found that in standard 7.5.2 said:

The keyword this names a pointer to the object for which an implicit object member function ([class.mfct.non.static]) is invoked or a non-static data member's initializer ([class.mem]) is evaluated.

but in 12.2.2 said constructors do not have implicit object parameter, then why I can use this pointer in constructor?

then I have several question comming, so my question is:

  1. Does the this pointer belongs to the class?

    I think the answer is NO, but I wanna confirm it.

  2. Does all class instance shared the constructors and destructor?

    I knew that the class instance will share the member function, does it same on constructors and destructor?

  3. How the this pointer was implemented?

    Is there something like virtual table to maintain the this pointer?

  4. Why I can use the this pointer in constructor?

    The this point to the implicit object, but constructor didn't have the implicit object parameter, then how could the this pointer worked well?

Any additional supplements and recommendations are appreciated.

Edit:

This stackoverflow helps me a lot : Does a constructor also have an implicit this parameter

CodePudding user response:

but I don't know how to implement it.

this pointer is a feature of the C language. If you aren't implementing C , then you don't need to "implement" this pointer. If you want to know how to implement C , there are open source C compilers available.

why I can use this pointer in constructor?

Constructor is a non-static member function. You can use this in non-static member functions.

but in 12.2.2 said constructors do not have implicit object parameter

Quoted rule is prefaced: For the purposes of overload resolution.... It doesn't apply to anything other than overload resolution.

  1. Does the this pointer belongs to the class?

There is no concept of "belongs" in the language.

  1. Does all class instance shared the constructors and destructor?

There is no concept of sharing functions in the language.

  1. How the this pointer was implemented?

The language doesn't describe how to implement itself. It describes how the program written in the language shall or may behave.

  1. Why I can use the this pointer in constructor?

See above.

  •  Tags:  
  • c
  • Related