-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

10
  • 6
    Because C++ is not Python. It's not really clear what sort of answer you are expecting here. Commented Nov 23, 2022 at 2:46
  • It actually does have a self parameter, but this is hidden from the coder Commented Nov 23, 2022 at 2: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 Commented Nov 23, 2022 at 2: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. Commented Nov 23, 2022 at 2:48
  • 1
    If your properties were public, you could check dog1.m_name and dog2.m_name Commented Nov 23, 2022 at 3:00

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.