+ 2

How to use the keyword "this" pointer in initialization list.

I'm trying to learn how to use the key word "this", the problem is that I don't know how to use "this" in initialization list. I have this code: https://code.sololearn.com/cX45QhgmyM2Y From lines 17-18 I got this error: expected identifier before ‘this’ this -> name(name), this -> race(race){} I don't know what is the proper way to use "this" in initialization list, how can I use "this" in initialization list? Also, I realized that from lines 21-22 doesn't gives me a compilation error, why? doing this is equivalent to the lines 25-28 right?, when I try to compile using only the lines 25-28, now I got a compilation error, and because of this, I'm forced to use "this" (lines 31-34). But I don't want to declare the members in the constructor body, that's why I'm using initialization list, but I don't know how to implement this... How can I implement it?

15th Dec 2018, 7:03 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
1 Réponse
+ 4
Using this as in line 17 & 18 is not supported. This is a valid usage. Name(first: string, last: string): first(first), last(last), initials(""+this->first[0]+this->last[0]) {} The first() is known to be this->first due to syntax. The enclosed first is known to be the parameter as it is not qualified with this and that is the closest scope.
16th Dec 2018, 5:44 PM
John Wells
John Wells - avatar