<p>In C++, you could refer to members of a class directly in its member functions. Many other languages requires an explicit <code>this.</code> or <code>this-&gt;</code> prefix, which is longer to write. I have also seen some projects in C++ that add an <code>m_</code> prefix to the member variables, implying they find something bad without the explicit prefix.</p>
<p>What are the pros and cons of not requiring this prefix?</p>

<scoping>
Pros and cons of automatically importing the scope of the object in the methods
CC BY-SA 4.0
2023-07-21T08:42:52.873Z
Is this about C++ or programming languages in general? In C++, there are also places around templates where parsing strictly requires it just because C++ templates are a bit strange in that regard.
feldentm
CC BY-SA 4.0
2023-07-21T08:47:51.900Z
@feldentm It's a question in general. But if there is a situation related templates, that makes it difficult to use implicit `this`, for valid reasons that is not because C++ is just designed as so, it may also apply to other languages with templates. So it is likely a valid con.
user23013
<p>Because, currently, all answers are cons. Let me try some pros. Obviously, there must be some if the feature is so common.</p>
<h3>Pro: Brevity</h3>
<p>The code contains less words and characters and is, thus, easier to read. In OOP languages, methods could easily require prefixing this before every data access which clearly won't help readability. Also, having them in a slightly different color then static entities is much faster to get then parsing &quot;this.&quot; as a human. Unless you are colorblind of course.</p>
<h3>Pro: Correct Abstraction</h3>
<p>Implicit this is a common feature in OOP languages. There, it is common to abstract behavior by data structures. The functions operating on them have the fields of their associated data structure at hand. Hence, it makes sense to allow accessing them like local variables.</p>

CC BY-SA 4.0
2023-07-20T18:02:24.913Z
2023-07-21T07:03:20.657Z
2023-07-21T07:03:20.657Z
feldentm
<p>I have a couple arguments for requiring it.</p>
<h2>Longer compile times</h2>
<p>Allowing implicit <code>this</code>/<code>self</code> means there's more places the compiler has to look to see whether the variable is in scope or not, and if so what its type is. This may seem like it's not that big of an issue, but I've run into Swift code where the type checker would time out if you used implicit <code>self</code> rather than saying it explicitly.</p>
<h2>Sometimes you need it anyways</h2>
<p>Consider this common pattern in Swift:</p>
<pre class="lang-swift prettyprint-override"><code>public struct Example {
  public var foo: Int
  public var bar: Int

  public init(foo: Int, bar: Int) {
    self.foo = foo
    self.bar = bar
  }
}
</code></pre>
<p>Swift allows you to leave <code>self</code> implicit, but without arbitrarily changing the names of the parameters to the <code>init</code>, there's no way to leave it implicit here. Note that the <code>foo:</code> and <code>bar:</code> here specify both the internal name and the external label; to change only the internal name would be</p>
<pre class="lang-swift prettyprint-override"><code>public struct Example {
  public var foo: Int
  public var bar: Int

  public init(foo _foo: Int, bar _bar: Int) {
    foo = _foo
    bar = _bar
  }
}
</code></pre>
<p>which is more effort than it's worth.</p>
<h2>Extension methods</h2>
<p>This one depends on the way you write extension methods. It doesn't apply to Swift- or Rust-style implementation blocks, but it does apply to C# extension methods.</p>
<p>Implicit <code>this</code> can't be used in extension methods in C#. Consider the following code:</p>
<pre class="lang-cs prettyprint-override"><code>public class Example
{
  public int X { get; set; }

  public Example(int x)
  {
    X = x;
  }

  public int Add1(Example other)
  {
    return X + other.X;
  }
}

public static class ExampleExtensions
{
  public static int Add2(this Example first, Example second)
  {
    return first.X + second.X;
  }
}
</code></pre>

CC BY-SA 4.0
2023-07-19T11:42:25.163Z
2023-07-19T11:42:25.163Z
Bbrk24
CC BY-SA 4.0
2023-07-19T11:46:11.443Z
I highly doubt that the difference in compile time will be noticable
mousetail 'he-him'
CC BY-SA 4.0
2023-07-19T11:47:23.180Z
@mousetail Feel free to believe that, but Swift's type checker disagrees, evidently.
Bbrk24
CC BY-SA 4.0
2023-07-19T12:01:30.260Z
One thing to add to extension methods is, you could omit `this` for `Add1()` in methods of `Example`, but not for `Add2()`, which is a surprise, but makes sense if they are trying to prevent code being broken by random extensions.
user23013
CC BY-SA 4.0
2023-07-20T08:54:22.553Z
@Bbrk24: The latter point (extension methods) seems to be a particular quirk of C#, at a glance. Is there a _fundamental_ reason for C# that would prevent using `this.` in extension methods? (Since neither Swift nor Rust suffer from this, I'm tempted to say no...)
Matthieu M.
CC BY-SA 4.0
2023-07-20T13:43:12.667Z
@MatthieuM. There's a difference in how Swift/Rust and C# handle extensions. In C#, `foo.Add2(bar)` is just syntactic sugar for `ExampleExtensions.Add2(foo, bar)`. In Swift, extensions can also be used to add conditional or retroactive protocol conformances, so an `extension` block may generate a new vtable. Rust is much the same as Swift, except that `impl` blocks are the _only_ way (modulo macros) to implement traits.
Bbrk24
CC BY-SA 4.0
2023-07-20T15:13:03.693Z
@Bbrk24: I see. It still feels "off-topic" for a question about implicit `this`, given that in the extension method the argument is given a name (`first`, here), and therefore there's no implicit object scope either way (hence of course, no implicit this to refer to the implicit scope).
Matthieu M.
CC BY-SA 4.0
2023-07-20T18:05:14.453Z
@Bbrk24 Could you please provide a link to some document explaining why the statement about Swift Compile time is correct? Usually, this is just a closed lookup when reaching the enclosing type in an open lookup which should not impose any significant performance impacts. I guess there are other concepts required to have the effect that Swift might have.
feldentm
CC BY-SA 4.0
2023-07-20T18:16:17.513Z
@feldentm I’ll see if I can find a repro later today, I can’t look right now. In the meantime I will mention that Swift allows overloading on return type alone which definitely doesn’t help.
Bbrk24
CC BY-SA 4.0
2023-07-20T20:05:34.680Z
@feldentm I'm struggling to reproduce the issue I remember encountering, but I'm also using a different OS and different hardware than I originally did it on. The type checker (at least in 5.6) is extremely sensitive to things like `["a"]+["b"]` vs `["a", "b"]`, so I wouldn't be surprised if I originally ran into it. Regardless, I can't find where I even got that idea from in the first place.
Bbrk24
CC BY-SA 4.0
2023-07-20T23:20:16.860Z
Swift type checking times are probably a bit of a red herring for other languages. Swift uses a global type inference algorithm that could cause it to search in a lot of possible matches if an identifier isn't explicitly scoped.  This results in notoriously odd performance issues when compiling code that seems perfectly fine ([example](https://forums.swift.org/t/regarding-swift-type-inference-compile-time-performance/49748/49)).
occipita
CC BY-SA 4.0
2023-07-20T23:57:23.040Z
@occipita That's entirely fair, and yeah that example is frankly absurd.
Bbrk24
CC BY-SA 4.0
2023-07-21T08:31:24.837Z
But then, I'd suggest adding the interaction with global typing to the answer. It is reasonable that increasing the state space in such languages can have notable effects.
feldentm
<p>It goes further than that. Another thing that C++ does here is to fix the type of <code>this</code> to be a pointer to the class type that the member function is a member of. So in:</p>
<pre><code>class Foo {
    void bar() {
        // type of this is always Foo*
    }
};
</code></pre>
<p>You might think that this is obvious, but it is more restrictive than you think. There are cases where you want <code>this</code> to be another type. For example, if you have inheritance, you might want the base class to do something with the derived class, without requiring virtual functions:</p>
<pre><code>struct Base {
    void do_something_with_derived() {
        this-&gt;foo();
    }
};

struct Derived: Base {
    void foo(); // non-virtual!
};

Derived bar;
bar.do_something_with_derived(); // works if this is Derived*
</code></pre>
<p>Another issue that plagues C++ is that <a href="https://en.cppreference.com/w/cpp/language/member_functions" rel="nofollow noreferrer">member functions</a> can have cvref qualifications, allowing you to make overloads for <code>const</code>, <code>volatile</code> and reference-qualified versions of an object of the class. For example, you want <code>operator[]</code> to return a <code>const</code> reference if the object is <code>const</code> and a non-<code>const</code> reference if the object is non-<code>const</code>. That means you have to make two overloads:</p>
<pre><code>class MyIntArray {
    int data[…];
public:
    int&amp; operator[](std::size_t index) { return data[index]; }
    const int&amp; operator[](std::size_t index) const { return data[index]; }
};
</code></pre>
<p>Notice how the body of those two functions is identical. This is a simple function, but for a more complex function you really want to avoid the code duplication. If the type of <code>this</code> is not determined by the function declaration itself, but by the type of object it is applied on, you could then create a templated version of <code>operator[]()</code> that deduces everything for you. This has been made possible in C++23 using the <a href="https://en.cppreference.com/w/cpp/language/member_functions#Explicit_object_parameter" rel="nofollow noreferrer">explicit object parameter</a>:</p>
<pre><code>class MyIntArray {
    int data[…];
public:
    auto&amp; operator[](this auto&amp;&amp; self, std::size_t index) {
        return self.data[index];
    }
};
</code></pre>

CC BY-SA 4.0
2023-07-19T14:46:58.670Z
2023-07-19T14:46:58.670Z
G. Sliepen
CC BY-SA 4.0
2023-07-19T16:52:55.367Z
While it's true that `this` could have more detailed types, notably in inheritable clone functions which may require `this` in a type in the template argument, I don't think it has anything to do with implicit or explicit `this`, as the implicit `this` usually shares the same type as the explicit one. If there is a case that it would be helpful to access `this` in different types by using different calls in the same function, it may have a point.
user23013
CC BY-SA 4.0
2023-07-20T00:44:22.913Z
You give examples where explicit `this` is helpful, but no one is arguing that explicit `this` shouldn't be allowed; the question is whether it should be mandatory in every case.
benrg
CC BY-SA 4.0
2023-07-20T07:02:51.523Z
Maybe this should be a new question then? Pros and cons of having a `this` with a non-fixed type?
G. Sliepen
CC BY-SA 4.0
2023-07-20T18:09:01.853Z
This answer should be deleted and moved to another question on explicit this *type* as it is not related to the question here. The explicit this type is also interesting and has completely different points against and in favor.
feldentm
CC BY-SA 4.0
2023-07-20T23:44:13.837Z
In order to make `Base::do_something_with_derived()` work as you expect, what should it compile to?  The only way I can see to make this work is to use virtual methods, or to make it a template method, both of which are available in the language but add overhead. C++'s ethos is to not add overhead without the programmer explicitly requesting it.  You can argue whether this is sensible or not (I'd suggest that methods should be virtual by default, for example), but you can't argue that this is a flawed design, as the language's explicit goal requires it to be this way.
occipita
CC BY-SA 4.0
2023-07-21T05:30:11.740Z
Semantically, it would make much more sense in C++ for `this` to be a reference rather than a pointer. However, it's a pointer because the `this` keyword was added to the language before references were, and it can't be fixed because of backwards compatibility concerns.
Karl Knechtel
<h2>Pro: Unification with closure functions</h2>
<p>Many languages have the feature called closure, that makes it possible to define a function inside another function, and use the variables in the other function. It is often used to write callback functions passed to other functions, which is usually short, and it usually makes sense to read them in the same context. So it is generally allowed to use variables in the outer scope directly.</p>
<p>If someone is extreme about unifying everything, they may want classes not looking too different from functions. It might become more confusing using the different ways, if someone writes a method function inside a class inside another function.</p>
<p>Seeing how many cons there are, this is probably not the right way. But it isn't obvious what a good alternative is like.</p>

CC BY-SA 4.0
2023-07-26T15:07:57.823Z
2023-07-26T15:07:57.823Z
user23013
<h1>Telling apart instance, local, and global vars</h1>
<p>In a statically-typed language such as Java or C++, we know ahead of time which variables are local variables, global variables, or instance variables. In dynamic languages this can be more difficult because they often allow the programmer to create new instance fields at run-time.</p>
<p>Many dynamic languages variables are global-by-default. Assigning to a variable that isn't in scope as a local variable will assign to a global variable. For example, in Javascript:</p>
<pre><code>x = 10      # global variable
this.x = 20 # instance variable
</code></pre>
<p>In Python, variables are local-by-default. If you assign to a name that's not already a local variable it will create a new local variable. We have to use <code>self.</code> to assign to instance variables, and a <code>global</code> annotation to assign to global variables.</p>
<pre><code>x = 10      # local variable
self.x = 10 # instance variable.
</code></pre>
<p>Some dynamic languages may choose to avoid the need for <code>this</code> by using dynamic scoping for all variables. The variable always checks the local, then instance, then global scope, in that order. The downside here is that in a dynamic language this scope may change at run-time if someone assigns a new field to the instance variable. This is can cause variables to unexpectedly change scope. It is also worse for performance, because the language doesn't know at compile-time where to look for the variable.</p>

CC BY-SA 4.0
2023-07-26T16:35:01.087Z
2023-07-26T16:50:43.180Z
2023-07-26T16:50:43.180Z
hugomg
<h2>Con: No computation on constructors before allocation</h2>
<pre class="lang-cs prettyprint-override"><code>public class Example
{
    public Example( int arg )
    {
        if ( arg &gt; MAX )
            throw new OutOfBoundsException(nameof(arg));
        this = new(); // Lots of very heavy properties
    }
}

</code></pre>
<h2>Con: No polymorphic super type instantiation</h2>
<pre class="lang-cs prettyprint-override"><code>public class Channel : ChannelInterface
{
    public Channel( int capacity = 0 )
    {
        if ( capacity &gt; 0 )
            this = new BoundedChannel( capacity );
        else
            this = new UnboundedChannel();
    }
}

</code></pre>

CC BY-SA 4.0
2023-07-19T13:30:01.100Z
2023-07-19T19:25:32.147Z
2023-07-19T19:25:32.147Z
André L F S Bacci
CC BY-SA 4.0
2023-07-19T13:47:45.533Z
I don't understand what you mean by "No computation on constructors"
mousetail 'he-him'
CC BY-SA 4.0
2023-07-19T14:14:31.423Z
This has nothing to do with `this = object`. This is about `this.foo = bar` as opposed to just `foo = bar` (with implicit `this.`).
Bbrk24
CC BY-SA 4.0
2023-07-19T19:29:16.027Z
Constructors _are_ methods, that implicit defines `this`. This answer goes a step further, by explicit requesting `this` allocation before explicit using this to open new functionality that otherwise is not possible with implicit defined implicit imported `this`.
André L F S Bacci
CC BY-SA 4.0
2023-07-19T19:49:22.737Z
Swift, which has implicit `self`, also lets you write `self =` in struct initializers (though not class initializers, for various reasons).
Bbrk24
CC BY-SA 4.0
2023-07-20T23:47:58.440Z
Both of these are consequences of precise details of the mechanism used to implement and allocate objects, not the choice of whether or not to require an explicit `this` reference when referring to members, so seem to not be answers to this question.
occipita
CC BY-SA 4.0
2023-07-21T08:40:10.643Z
The answer is about assigning something to this. It is also about the question if a constructor would return this. AFAIK, most languages have immutable this and have constructor realization typed as as (this.type, ...) : void. The memory allocation happens before the constructor call. Constructors aren't to be confused with factory methods.
feldentm
<h2>Con: Aliasing between instance and local variables</h2>
<p>Especially for constructors, you often need both variables and instance method with the same names:</p>
<pre><code>Klass(int version, string name, bool isAlive) {
    this.version = version;
    this.name =  name;
    this.isAlive = isAlive;
}
</code></pre>
<p>In this case you could not use the prefix syntax. People often use slightly different names like a <code>m_</code> prefix so they can use the shorter syntax.</p>
<p>It would be more consistent if you could use the same syntax everywhere.</p>
<h2>Con: Inability to see what has temporary or permanent effect at a glance.</h2>
<p>Suppose you are reading a long method and it looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>                      foreach (Item item in allItems) {
                           if (item.property = filter) {
                                goodItems.push(item)
                           }
                      }
</code></pre>
<p>You can't tell from this bit of code if <code>allItems</code>, <code>filter</code> or <code>goodItems</code> is just a temporary variable or stored in the instance.</p>
<p>To make things worse there could be a <code>goodItems</code> in the instance but this is just a local variable with the same name.</p>
<p>Assigning to instance attributes are <strong>side effects</strong>, one of the more important things to look for when trying to understand a function. Giving them a <code>this.</code> prefix makes it easier to identify these side effects.</p>
<h2>A naming convention that separates locals from properties goes a long way to solve both issues.</h2>

CC BY-SA 4.0
2023-07-19T11:42:02.360Z
2023-07-19T11:45:39.917Z
2023-07-19T11:45:39.917Z
mousetail 'he-him'
CC BY-SA 4.0
2023-07-19T11:44:00.837Z
I also included that first one in my answer, oh well. I'll note that neither of these apply to C# which uses a different naming convention for locals (camelCase) vs properties (PascalCase).
Bbrk24
CC BY-SA 4.0
2023-07-20T17:54:25.463Z
The first one is not correct with optional this nothing is permanently hidden. The second one assumes no semantic syntax highlighting, which is a common feature these days. Those are still valid points explaining dates style guides.
feldentm
CC BY-SA 4.0
2023-07-20T23:07:52.093Z
*You can't tell from this bit of code if allItems, filter or goodItems is just a temporary variable or stored in the instance* -- maybe not if presented like this, but I use an IDE that's smart enough to give instance variables a different colour to others, and the existence of this feature kind-of negates this point for most scenarios, I think.
occipita
CC BY-SA 4.0
2023-07-21T05:27:46.927Z
C++ mitigates the first issue using initialization lists: `Klass(int version, string name, bool isAlive): version(version), name(name), isAlive(isAlive) {}` works seamlessly because in each context where the identifiers appear, exactly one of the meanings is valid. It's presumably not the easiest thing to parse, but C++ is overall not easy to parse.
Karl Knechtel
# Pros and cons of automatically importing the scope of the object in the methods
Posted by: username_0 on 2023-07-19
In C++, you could refer to members of a class directly in its member functions. Many other languages requires an explicit `this.` or `this->` prefix, which is longer to write. I have also seen some projects in C++ that add an `m_` prefix to the member variables, implying they find something bad without the explicit prefix.

What are the pros and cons of not requiring this prefix?
**Tags:** scoping
> **Comments:**
> **username_1**: Is this about C++ or programming languages in general? In C++, there are also places around templates where parsing strictly requires it just because C++ templates are a bit strange in that regard.  
> **username_0**: @feldentm It's a question in general. But if there is a situation related templates, that makes it difficult to use implicit `this`, for valid reasons that is not because C++ is just designed as so, it may also apply to other languages with templates. So it is likely a valid con.  
---
## 7 answers
### Answer by username_3 on 2023-07-19. Score: 11 | Accepted answer
Con: Aliasing between instance and local variables
Especially for constructors, you often need both variables and instance method with the same names:
Klass(int version, string name, bool isAlive) {
    this.version = version;
    this.name =  name;
    this.isAlive = isAlive;
}

In this case you could not use the prefix syntax. People often use slightly different names like a m_ prefix so they can use the shorter syntax.
It would be more consistent if you could use the same syntax everywhere.
Con: Inability to see what has temporary or permanent effect at a glance.
Suppose you are reading a long method and it looks like this:
                      foreach (Item item in allItems) {
                           if (item.property = filter) {
                                goodItems.push(item)
                           }
                      }

You can't tell from this bit of code if allItems, filter or goodItems is just a temporary variable or stored in the instance.
To make things worse there could be a goodItems in the instance but this is just a local variable with the same name.
Assigning to instance attributes are side effects, one of the more important things to look for when trying to understand a function. Giving them a this. prefix makes it easier to identify these side effects.
A naming convention that separates locals from properties goes a long way to solve both issues.
> **Comments:**
> **username_2** (2023-07-19): I also included that first one in my answer, oh well. I'll note that neither of these apply to C# which uses a different naming convention for locals (camelCase) vs properties (PascalCase).  
> **username_1** (2023-07-20): The first one is not correct with optional this nothing is permanently hidden. The second one assumes no semantic syntax highlighting, which is a common feature these days. Those are still valid points explaining dates style guides.  
> **username_5** (2023-07-20): *You can't tell from this bit of code if allItems, filter or goodItems is just a temporary variable or stored in the instance* -- maybe not if presented like this, but I use an IDE that's smart enough to give instance variables a different colour to others, and the existence of this feature kind-of negates this point for most scenarios, I think.  
> **username_8** (2023-07-21): C++ mitigates the first issue using initialization lists: `Klass(int version, string name, bool isAlive): version(version), name(name), isAlive(isAlive) {}` works seamlessly because in each context where the identifiers appear, exactly one of the meanings is valid. It's presumably not the easiest thing to parse, but C++ is overall not easy to parse.  
---
### Answer by username_2 on 2023-07-19. Score: 8
I have a couple arguments for requiring it.
Longer compile times
Allowing implicit this/self means there's more places the compiler has to look to see whether the variable is in scope or not, and if so what its type is. This may seem like it's not that big of an issue, but I've run into Swift code where the type checker would time out if you used implicit self rather than saying it explicitly.
Sometimes you need it anyways
Consider this common pattern in Swift:
public struct Example {
  public var foo: Int
  public var bar: Int

  public init(foo: Int, bar: Int) {
    self.foo = foo
    self.bar = bar
  }
}

Swift allows you to leave self implicit, but without arbitrarily changing the names of the parameters to the init, there's no way to leave it implicit here. Note that the foo: and bar: here specify both the internal name and the external label; to change only the internal name would be
public struct Example {
  public var foo: Int
  public var bar: Int

  public init(foo _foo: Int, bar _bar: Int) {
    foo = _foo
    bar = _bar
  }
}

which is more effort than it's worth.
Extension methods
This one depends on the way you write extension methods. It doesn't apply to Swift- or Rust-style implementation blocks, but it does apply to C# extension methods.
Implicit this can't be used in extension methods in C#. Consider the following code:
public class Example
{
  public int X { get; set; }

  public Example(int x)
  {
    X = x;
  }

  public int Add1(Example other)
  {
    return X + other.X;
  }
}

public static class ExampleExtensions
{
  public static int Add2(this Example first, Example second)
  {
    return first.X + second.X;
  }
}
> **Comments:**
> **username_3** (2023-07-19): I highly doubt that the difference in compile time will be noticable  
> **username_2** (2023-07-19): @mousetail Feel free to believe that, but Swift's type checker disagrees, evidently.  
> **username_0** (2023-07-19): One thing to add to extension methods is, you could omit `this` for `Add1()` in methods of `Example`, but not for `Add2()`, which is a surprise, but makes sense if they are trying to prevent code being broken by random extensions.  
> **username_4** (2023-07-20): @Bbrk24: The latter point (extension methods) seems to be a particular quirk of C#, at a glance. Is there a _fundamental_ reason for C# that would prevent using `this.` in extension methods? (Since neither Swift nor Rust suffer from this, I'm tempted to say no...)  
> **username_2** (2023-07-20): @MatthieuM. There's a difference in how Swift/Rust and C# handle extensions. In C#, `foo.Add2(bar)` is just syntactic sugar for `ExampleExtensions.Add2(foo, bar)`. In Swift, extensions can also be used to add conditional or retroactive protocol conformances, so an `extension` block may generate a new vtable. Rust is much the same as Swift, except that `impl` blocks are the _only_ way (modulo macros) to implement traits.  
> **username_4** (2023-07-20): @Bbrk24: I see. It still feels "off-topic" for a question about implicit `this`, given that in the extension method the argument is given a name (`first`, here), and therefore there's no implicit object scope either way (hence of course, no implicit this to refer to the implicit scope).  
> **username_1** (2023-07-20): @Bbrk24 Could you please provide a link to some document explaining why the statement about Swift Compile time is correct? Usually, this is just a closed lookup when reaching the enclosing type in an open lookup which should not impose any significant performance impacts. I guess there are other concepts required to have the effect that Swift might have.  
> **username_2** (2023-07-20): @feldentm I’ll see if I can find a repro later today, I can’t look right now. In the meantime I will mention that Swift allows overloading on return type alone which definitely doesn’t help.  
> **username_2** (2023-07-20): @feldentm I'm struggling to reproduce the issue I remember encountering, but I'm also using a different OS and different hardware than I originally did it on. The type checker (at least in 5.6) is extremely sensitive to things like `["a"]+["b"]` vs `["a", "b"]`, so I wouldn't be surprised if I originally ran into it. Regardless, I can't find where I even got that idea from in the first place.  
> **username_5** (2023-07-20): Swift type checking times are probably a bit of a red herring for other languages. Swift uses a global type inference algorithm that could cause it to search in a lot of possible matches if an identifier isn't explicitly scoped.  This results in notoriously odd performance issues when compiling code that seems perfectly fine ([example](https://forums.swift.org/t/regarding-swift-type-inference-compile-time-performance/49748/49)).  
> **username_2** (2023-07-20): @occipita That's entirely fair, and yeah that example is frankly absurd.  
> **username_1** (2023-07-21): But then, I'd suggest adding the interaction with global typing to the answer. It is reasonable that increasing the state space in such languages can have notable effects.  
---
### Answer by username_1 on 2023-07-20. Score: 4
Because, currently, all answers are cons. Let me try some pros. Obviously, there must be some if the feature is so common.

### Pro: Brevity

The code contains less words and characters and is, thus, easier to read. In OOP languages, methods could easily require prefixing this before every data access which clearly won't help readability. Also, having them in a slightly different color then static entities is much faster to get then parsing "this." as a human. Unless you are colorblind of course.

### Pro: Correct Abstraction

Implicit this is a common feature in OOP languages. There, it is common to abstract behavior by data structures. The functions operating on them have the fields of their associated data structure at hand. Hence, it makes sense to allow accessing them like local variables.
---
### Answer by username_6 on 2023-07-19. Score: 3
It goes further than that. Another thing that C++ does here is to fix the type of this to be a pointer to the class type that the member function is a member of. So in:
class Foo {
    void bar() {
        // type of this is always Foo*
    }
};

You might think that this is obvious, but it is more restrictive than you think. There are cases where you want this to be another type. For example, if you have inheritance, you might want the base class to do something with the derived class, without requiring virtual functions:
struct Base {
    void do_something_with_derived() {
        this->foo();
    }
};

struct Derived: Base {
    void foo(); // non-virtual!
};

Derived bar;
bar.do_something_with_derived(); // works if this is Derived*

Another issue that plagues C++ is that member functions can have cvref qualifications, allowing you to make overloads for const, volatile and reference-qualified versions of an object of the class. For example, you want operator[] to return a const reference if the object is const and a non-const reference if the object is non-const. That means you have to make two overloads:
class MyIntArray {
    int data[…];
public:
    int& operator[](std::size_t index) { return data[index]; }
    const int& operator[](std::size_t index) const { return data[index]; }
};

Notice how the body of those two functions is identical. This is a simple function, but for a more complex function you really want to avoid the code duplication. If the type of this is not determined by the function declaration itself, but by the type of object it is applied on, you could then create a templated version of operator[]() that deduces everything for you. This has been made possible in C++23 using the explicit object parameter:
class MyIntArray {
    int data[…];
public:
    auto& operator[](this auto&& self, std::size_t index) {
        return self.data[index];
    }
};
> **Comments:**
> **username_0** (2023-07-19): While it's true that `this` could have more detailed types, notably in inheritable clone functions which may require `this` in a type in the template argument, I don't think it has anything to do with implicit or explicit `this`, as the implicit `this` usually shares the same type as the explicit one. If there is a case that it would be helpful to access `this` in different types by using different calls in the same function, it may have a point.  
> **username_7** (2023-07-20): You give examples where explicit `this` is helpful, but no one is arguing that explicit `this` shouldn't be allowed; the question is whether it should be mandatory in every case.  
> **username_6** (2023-07-20): Maybe this should be a new question then? Pros and cons of having a `this` with a non-fixed type?  
> **username_1** (2023-07-20): This answer should be deleted and moved to another question on explicit this *type* as it is not related to the question here. The explicit this type is also interesting and has completely different points against and in favor.  
> **username_5** (2023-07-20): In order to make `Base::do_something_with_derived()` work as you expect, what should it compile to?  The only way I can see to make this work is to use virtual methods, or to make it a template method, both of which are available in the language but add overhead. C++'s ethos is to not add overhead without the programmer explicitly requesting it.  You can argue whether this is sensible or not (I'd suggest that methods should be virtual by default, for example), but you can't argue that this is a flawed design, as the language's explicit goal requires it to be this way.  
> **username_8** (2023-07-21): Semantically, it would make much more sense in C++ for `this` to be a reference rather than a pointer. However, it's a pointer because the `this` keyword was added to the language before references were, and it can't be fixed because of backwards compatibility concerns.  
---
### Answer by username_0 on 2023-07-26. Score: 1
## Pro: Unification with closure functions

Many languages have the feature called closure, that makes it possible to define a function inside another function, and use the variables in the other function. It is often used to write callback functions passed to other functions, which is usually short, and it usually makes sense to read them in the same context. So it is generally allowed to use variables in the outer scope directly.

If someone is extreme about unifying everything, they may want classes not looking too different from functions. It might become more confusing using the different ways, if someone writes a method function inside a class inside another function.

Seeing how many cons there are, this is probably not the right way. But it isn't obvious what a good alternative is like.
---
### Answer by username_9 on 2023-07-26. Score: 1
Telling apart instance, local, and global vars
In a statically-typed language such as Java or C++, we know ahead of time which variables are local variables, global variables, or instance variables. In dynamic languages this can be more difficult because they often allow the programmer to create new instance fields at run-time.
Many dynamic languages variables are global-by-default. Assigning to a variable that isn't in scope as a local variable will assign to a global variable. For example, in Javascript:
x = 10      # global variable
this.x = 20 # instance variable

In Python, variables are local-by-default. If you assign to a name that's not already a local variable it will create a new local variable. We have to use self. to assign to instance variables, and a global annotation to assign to global variables.
x = 10      # local variable
self.x = 10 # instance variable.

Some dynamic languages may choose to avoid the need for this by using dynamic scoping for all variables. The variable always checks the local, then instance, then global scope, in that order. The downside here is that in a dynamic language this scope may change at run-time if someone assigns a new field to the instance variable. This is can cause variables to unexpectedly change scope. It is also worse for performance, because the language doesn't know at compile-time where to look for the variable.
---
### Answer by username_10 on 2023-07-19. Score: -2
Con: No computation on constructors before allocation
public class Example
{
    public Example( int arg )
    {
        if ( arg > MAX )
            throw new OutOfBoundsException(nameof(arg));
        this = new(); // Lots of very heavy properties
    }
}


Con: No polymorphic super type instantiation
public class Channel : ChannelInterface
{
    public Channel( int capacity = 0 )
    {
        if ( capacity > 0 )
            this = new BoundedChannel( capacity );
        else
            this = new UnboundedChannel();
    }
}
> **Comments:**
> **username_3** (2023-07-19): I don't understand what you mean by "No computation on constructors"  
> **username_2** (2023-07-19): This has nothing to do with `this = object`. This is about `this.foo = bar` as opposed to just `foo = bar` (with implicit `this.`).  
> **username_10** (2023-07-19): Constructors _are_ methods, that implicit defines `this`. This answer goes a step further, by explicit requesting `this` allocation before explicit using this to open new functionality that otherwise is not possible with implicit defined implicit imported `this`.  
> **username_2** (2023-07-19): Swift, which has implicit `self`, also lets you write `self =` in struct initializers (though not class initializers, for various reasons).  
> **username_5** (2023-07-20): Both of these are consequences of precise details of the mechanism used to implement and allocate objects, not the choice of whether or not to require an explicit `this` reference when referring to members, so seem to not be answers to this question.  
> **username_1** (2023-07-21): The answer is about assigning something to this. It is also about the question if a constructor would return this. AFAIK, most languages have immutable this and have constructor realization typed as as (this.type, ...) : void. The memory allocation happens before the constructor call. Constructors aren't to be confused with factory methods.  
---
