this pointer - C++
Quote:
The this pointer is a hidden pointer inside every class's non-static function which points to the class's particular object through which the concerned function is called.
Code:
class A { private: int rollNumber; public: A (int rollNum) { rollNumber = rollNum; } void setRollNumber (int rollNum) { rollNumber = rollNum; } }; int main () { A obj (1); obj.setRollNumber (2); }
class, C++ internally passes a reference of that object
as an additional parameter to the function. Therefore,
this function call `obj.setRollNumber (2);` will
internally look like:
Code:
obj.setRollNumber (&obj, 2);
Code:
void setRollNumber (A *const this, int rollNum) { this->rollNumber = rollNum; }
was implicitly passed to the function by C++.
Example:
Code:
class B { private: int sum; public: B (int number) { sum = 0; sum =+ number; } void add (int number) { sum =+ number; } }; int main () { B obj (1); // One way of adding the numbers is by calling the function `add ()` individually three times through the object `obj`. obj.add (2); obj.add (3); obj.add (4); }
Example:
Code:
class B { private: int sum; public: B () { sum = 0; } B& add (int number) { sum =+ number; // Returning the reference to the object through which this function will get called. return *this; } }; int main () { B obj; obj.add (1).add (2).add (3). add (4); }
call to `obj.add (1)` returns a reference to the `obj`. Through this reference
`add (2)` is called, so on and so forth. The constructor doesn't return
anything so this pattern of calling can't be applied to `B obj;`.
Quote:
this is a const pointer which means that you can change the value of the object it points to, but you can not make it point to something else!
Total Comments 0