This pointer

478 views
405 views

Published on

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

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
478
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
42
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

This pointer

  1. 1. I N T R O D U C T I O N U S I N G T H I S F O R R E T U R N I N G V A L U E S U S I N G T H I S F O R S P E C I F Y I N G M E M O R Y A D D R E S S U S I N G T H I S F O R A C C E S S I N G D A T A M E M B E R S This Pointer
  2. 2. 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 into existence with the value of this set to the address of the object for which it is called
  3. 3. 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
  4. 4. 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; }
  5. 5. void main() { clrscr(); num obj1(1,2),obj2(3,4); obj1.display(); obj2.display(); obj1.add(obj2); obj1.display(); getch(); }
  6. 6. OUTPUT
  7. 7. 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
  8. 8. 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(); }
  9. 9. OUTPUT
  10. 10. 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(>)
  11. 11. 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(); }
  12. 12. OUTPUT

×