This pointer

KamalAcharya 4,632 views 12 slides Apr 14, 2014
Slide 1
Slide 1 of 12
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12

About This Presentation

Brief summary of the functions of this pointer in C++.


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; }

void main() { clrscr (); num obj1(1,2),obj2(3,4); obj1.display (); obj2.display (); obj1.add(obj2 ); obj1.display (); getch (); }

OUTPUT

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 (); }

OUTPUT