-3

I am a beginner of C++ with Python background. I have some ambiguity about the process of obtaining instance attributes in Python classes and C++ classes.

As follows, I list two classes that have the same function in Python and C++ respectively.

My problem is that I am used to using self parameters to distinguish class attributes and instance attributes, and to ensure that instance attributes between different instances do not interfere with each other. But I do not know how C++ can do this without self parameters.enter image description here

I hope someone can explain in detail how C++achieves “self” without self, and what happens in under the hood?

Thanks

Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39
Ili a
  • 1
  • 1
  • 6
    Because C++ is not Python. It's not really clear what sort of answer you are expecting here. – juanpa.arrivillaga Nov 23 '22 at 02:46
  • It actually does have a `self` parameter, but this is hidden from the coder – Samathingamajig Nov 23 '22 at 02:46
  • 1
    Python is in the minority of languages that expose the `this`/`self` parameter, a lot of languages (C++, Java, JavaScript, C#, Ruby) don't – Samathingamajig Nov 23 '22 at 02:47
  • C++ has scoping rules about how names are resolved which allow it to decide when a variable is referring to an instance variable of the class, once that is decided at compilation time, then attributes work much the same (well, not exactly the same). C++ has quite different scoping rules from Python's scoping rules. – juanpa.arrivillaga Nov 23 '22 at 02:48
  • Read about [this pointer](https://stackoverflow.com/questions/4483653/can-you-explain-the-concept-of-the-this-pointer) in your favorite [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Also [What is the 'this' pointer?](https://stackoverflow.com/questions/16492736/what-is-the-this-pointer). Also read about **"implicit object parameter"**. – Jason Nov 23 '22 at 02:54
  • In your image, the C++ m_name is not a local variable in the constructor, but rather the instance property. The declaration "string m_name" is not inside the constructor. – qrsngky Nov 23 '22 at 02:55
  • 1
    If your properties were public, you could check `dog1.m_name` and `dog2.m_name` – qrsngky Nov 23 '22 at 03:00
  • You could write `this -> m_name = name;` in the constructor but it's not necessary. The declaration of `string m_name` is inside the `private` so it's obvious that it's instance property. – qrsngky Nov 23 '22 at 03:05
  • For "class properties", read about static members of a C++ class. – qrsngky Nov 23 '22 at 03:07
  • Also [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors/285557#285557) – Ranoiaetep Nov 23 '22 at 03:54

1 Answers1

0

c++ just doesn't write "self" explicitly, maybe you need to learn about the keyword "this".

veekxt
  • 372
  • 1
  • 9