educative.io

Educative

https://www.educative.io/module/lesson/object-oriented-programming/R1rlOWy3WxO

Q) Why do we have to use this in every method here, why can’t we directly use num1 and num2 in all the function as already we have initialized it in the constructor itself?
return this.num2 / this.num1;


Type your question above this line.

Course: https://www.educative.io/collection/10370001/5692479535841280
Lesson: https://www.educative.io/collection/page/10370001/5692479535841280/6742287721693184

Every object has access to its own address through an essential pointer known as this pointer. All member functions take this pointer as an implicit argument. As a result, this may be used to refer to the calling object within a member function.

Data members are duplicated for each object, and all objects share member functions.
The next concern is how the correct data members are retrieved and changed if only one copy of each member function exists and is utilised by numerous objects.
The compiler provides an implicit pointer as well as the names of the functions as ‘this’.
All nonstatic member function calls get the ‘this’ pointer as a secret parameter, and it is available as a local variable within the body of all nonstatic functions. Because static member functions can be called without any object, the ‘this’ reference is not accessible (with class name).

In our example function parameter and class data members names are same, therefore we use 'this' pointer to specify the class data members