-4

while defining a constructor outside class, this keyword is not used to create variables.

Person::Person(int initialAge){
        // Add some more code to run some checks on initialAge
        if(initialAge > 0){
            this.age = initialAge;
        }else{
            this.age =0;
        }

    }
kush_55
  • 11
  • 4
    This does not compile. `this->age` could. Please post [mcve] and state your question. Using or not using `this` has nothing to do where any method is declared. – Quimby Jun 13 '19 at 10:55
  • strictly speaking you never use the `this` keyword to "create variables". what exactly are you refering to? The question is rather unclear, because your example is not inline but still has the keyword `this` – 463035818_is_not_an_ai Jun 13 '19 at 11:19

1 Answers1

3

The fact that you define your constructor in the way you do makes no odds on whether or not you use this.

this can be used to disambiguate between a local variable or a class member.

Since there is no local variable age in scope, the language assumes you are referring to a class member, so this is superfluous, although some folk retain it for purported clarity.

In C++ you'd need to write this->age to access the member, or the less clear (*this).age.

You constructor could be written as

Person::Person(int initialAge) : age(std::max(0, initialAge))
{
}

Reference: Benefits of Initialization lists

Bathsheba
  • 231,907
  • 34
  • 361
  • 483