2

I'm experienced in Python and now learning cpp to speed up code. After reading a bit this seems to be the cpp equivalent of self. I found a question explaining the difference from a cpp user's point of view but I'd like to know any differences for a python user's point of view.

  • 7
    `this` is a keyword in the c++ syntax and has special meaning. `self` is not a keyword in python, its just a common variable name people use when refering to their class instance for exmaple. but you are not forced to use the word `self` you could call it anything you want but convention says you "should" call it `self` – Chris Doyle Feb 26 '20 at 12:40
  • There are no more differences to the best of my knowledge. The differences are just technical - in `Python` you have to receive the parameter as an argument, and it is always the first one to the method. The naming convention is just that. – kabanus Feb 26 '20 at 12:41
  • Does this answer your question? [Use of "this" keyword in C++](https://stackoverflow.com/questions/6779645/use-of-this-keyword-in-c) – mkrieger1 Feb 26 '20 at 12:56

2 Answers2

2

The major difference is that you mostly don't need this in C++, because there is a syntactic distinction between defining a member and referring to it.

Contrast

Python:

class Foo:
    def __init__(self):
        self._bar = 42

    def baz(self):
        return self._bar += 1

C++:

class Foo {
    int bar = 42;
public:
    int baz() { return bar += 1; }
}
Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
Caleth
  • 52,200
  • 2
  • 44
  • 75
2

In addition to the answer already given, self in Python is just a conventional name chosen for the first argument of a class method which refers to the object itself that the method is called on directly.

In C++, this is a keyword that is not explicitly specified as a parameter of a non-static class member function, but automatically refers to the instance that such a function is called on as pointer.

That means this is not a reference to the object, but a pointer to it. So

this.member = 4;

is not possible. this must be dereferenced first to obtain a reference to the object from the pointer:

this->member = 4;

or (uncommonly)

(*this).member = 4;

With a few exceptions relating to name lookup in templates, the names of members refer to the current instances member automatically, as explained in the other answer, so this-> can be dropped, usually:

member = 4;
walnut
  • 21,629
  • 4
  • 23
  • 59