'this' pointer in c++

C++ this pointer

What is 'This' pointer in C++:

In c++ this pointer means Every object has access to its own address through an important pointer is called this pointer. When a member function is called, this pointer automatically passed an implicit argument that is a pointer to the invoking object.

Example program for this pointer in c++:

#include < iostream > using namespace std; class pwr { double b; int e; double val; public: pwr(double base, int ex); double get_pwr() { return val; } }; pwr::pwr(double base, int ex) { b = base; e = ex; val = 1; if(exp==0) return; for( ; ex>0; ex--) val = val * b; } int main() { pwr x(4.0, 2), y(2.5, 1), z(5.7, 0); cout << x.get_pwr() << " "; cout << y.get_pwr() << " "; cout << z.get_pwr() << "\n"; return 0; }


16 2.5 1

Within a member function, The member of the class can be accessed directly. Inside pwr the statement
b = base
Which means, the copy of the b associated with the invoking object, the however same statement is written like this
this->b = base
This pointer points to the object that invoked pwr ().

Here the entire pwr constructor is written using this pointer

pwr :: pwr(double base, int ex)
this->b = base;
this->e = ex;
this->val = 1;
for(; ex>0; ex--)
this->val = this->val * this->b;


Actually, no c++ program would be written like this, showing purpose we write this. the standard form is easier than this.

Recommended Posts:

Post a Comment