Brief summary of the functions of this pointer in C++.
Size: 120.19 KB
Language: en
Added: Apr 14, 2014
Slides: 12 pages
Slide Content
Introduction Using this for returning values Using this for specifying memory address Using this for accessing data members This Pointer
Introduction Every member function of the class is born with the pointer called this which points to the object with which member function is associated. When a member function is invoked it comes int o existence with the value of this set to the address of the object for which it is called
Using this for returning values This pointer can be used to return the values from the member function. Since it points to the address of the object which called the member function, we can return the object by value with the help of this pointer
Sample Program #include< iostream.h > #include< conio.h > class num { int a,b ; public : num( int x, int y) { a= x;b =y ; } void display() { cout <<"a="<<a<<" and b="<<b<< endl ; } num add(num); }; num num:: add(num x) { a=a+x.a; b=b+x.b ; return *this; }
Using this for specifying memory address This pointer is created automatically inside the member function whenever the member function is invoked by the object. It holds the memory address of the object so it can be used to access the memory address of the object
Sample Program #include< iostream.h > #include< conio.h > class num { int a; public : void displayAddress () { cout <<"The memory address of the object is "<< this<< endl ; } }; void main() { clrscr (); num obj1,obj2; obj1.displayAddress (); obj2.displayAddress (); getch (); }
OUTPUT
Using this pointer for accessing the data member This pointer can also be used to access the data members inside the member function. It can be done with the help of arrow operator(->) Arrow operator is the combination of hyphen(-) and greater than operator(>)
Sample Program # include< iostream.h > #include< conio.h > class num { int a; public : void display() { this- >a=89; cout <<"a= "<< this->a << endl ; } }; void main() { clrscr (); num obj1; obj1.display (); getch (); }