473,473 Members | 1,563 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

this pointer

13 New Member
Hi all,

can u explain about this pointer with example...

how to use and where to use?

how can we return objects with this pointer?
Jan 12 '07 #1
6 1749
Banfa
9,065 Recognized Expert Moderator Expert
this is a keyword in C++ that evaluates to a pointer to the current object.

It is only valid inside non-static member functions of a class (or struct).

These functions can return this (a pointer to the object) or *this (the object or a reference to the object depending on how the function is declared).
Jan 12 '07 #2
macklin01
145 New Member
I've only needed the this pointer on rare occasions. Here's an example (but shortened):

Suppose you have a Contour class that contains a linked list of data points and pointers to previous and next contours. Something like this:
Expand|Select|Wrap|Line Numbers
  1. class Contour{
  2. private:
  3.  DataPoint* pFirstDataPoint;
  4.  bool IsClosed;
  5.  Contour* pPreviousContour;
  6.  Contour* pNextContour;
  7. public:
  8.  Contour();
  9.  ~Contour();
  10.  bool CleanContour( void );
  11.  // etc
  12. };
  13.  
Suppose that you want the CleanContour() function to remove all contours prior to and after the object, but not the object. Then you might do something like this:

Expand|Select|Wrap|Line Numbers
  1. bool Contour::CleanContour( void )
  2. {
  3.  Contour* pCurrentContour = this;
  4.  // find the "first" contour
  5.  while( pCurrentContour->pPreviousContour )
  6.  { pCurrentContour = pCurrentContour->pPreviousContour; }
  7.  
  8.  // delete all contours but this one
  9.  
  10.  while( pCurrentContour )
  11.  {
  12.   Contour* pTemp = pCurrentContour->pNextContour;
  13.   if( pCurrentContour != this )
  14.   { delete pCurrentContour; }
  15.   pCurrentContour = pTemp;
  16.  }
  17.  pPreviousContour = NULL;
  18.  pNextContour = NULL;
  19.  return true;
  20. }
  21.  
So, what's going on here is that we're first going as far back along the linked list as we can, then progressing forward and deleting everything, taking care to not delete our current object.

Yes, this could have been done differently without this "this" pointer. (Delete backward, then delete forward.) However, there are cases where the "this" keyword is helpful for identifying when you've reached the current object, and this illustrates how to use it.

Another potential use: print out "this" as part of an error message to identify the memory address of an object that causes an error.

I hope this is somewhat helpful. -- Paul
Jan 13 '07 #3
Banfa
9,065 Recognized Expert Moderator Expert
You use this a bit when overloading operators because you are often expected to return a reference to the object just operated on.
Jan 13 '07 #4
ramudukamudu
16 New Member
Hi all,

can u explain about this pointer with example...

how to use and where to use?

how can we return objects with this pointer?
Hi, When objects are created, memory will be allocated only for data members. member funcitons will be stored seperately(this avoids unnecessary duplication). If you r going to invoke a member funciton, reference of the object is passed to the member function through a pointer called "this". For a class of type "Circle", "this" will be "Circle* const this". So "this" pointer is automatically created once you invoke the member funciton.

Uses:
1> If the arguments of the constructors clash with the member functions:
class Circle
{
float radius;
Circle(float radius)
{
this.radius = radius;
}
..................
2> During operator overloading if you want to return the result


Complex & Complex::operator +=(Complex temp) {
re += temp . re ;
im += temp .im ;
return * this ;
}
Jan 13 '07 #5
nandeshwar
4 New Member
Hi all,

can u explain about this pointer with example...

how to use and where to use?

how can we return objects with this pointer?

I am writing two programs that may help you understanding usage of this pointer,
Expand|Select|Wrap|Line Numbers
  1. #include<iostream.h>
  2. #include<conio.h>
  3. #include<string.h>
  4. class Test
  5. {
  6.    private:
  7.          int id;
  8.          char name[30];
  9.    public:
  10.        Test(int id,char name[30])
  11.         {                                // id is local variabe as well as instance variable
  12.            this->id=id;                //  "this->id" means object id or instance id
  13.            strcpy(this->name,name);  // "id" means local id in this function
  14.        }                                          
  15.     void display()
  16.     {
  17.        cout<<id<<endl;
  18.        cout<<name<<endl;
  19.    }
  20. };
  21.  
  22. void main()
  23. {
  24.      Test t(1,"Nandeshwar");
  25.       t.display();
  26.       getch();
  27. }
  28.  
  29.  
  30. Another Program 
  31.  
  32. #include<iostram.h>
  33. #include<conio.h>
  34.  
  35. class Test
  36. {
  37.      private:
  38.         int id,age;
  39.      public:
  40.            Test()
  41.             {
  42.             }
  43.           Test(int id,int age)
  44.            {
  45.               this->id=id;
  46.               this->age=age;
  47.            }
  48.             void display()
  49.             {
  50.                 cout<<"Id: "<<id<<"is senior person of age"<<age<<endl;
  51.              }
  52.           Test operator>(Test t2);
  53. };
  54. Test Test::operator>(Test t2)
  55. {
  56.      if(age>t2.age)
  57.             return *this; //here returning first object
  58.      else
  59.          return t2;     //here we are returning 2nd object i.e. t2
  60. }
  61.  
  62. void main()
  63. {
  64.    clrscr();
  65.    Test t1(1,29);
  66.    Test t2(2,25);
  67.    Test t3;
  68.  
  69.   t3=t1>t2;
  70.   t3.display();
  71.   getch();
  72. }
  73.  
Jan 14 '07 #6
ogedezvoltare
18 New Member
Uses:
1> If the arguments of the constructors clash with the member functions:

}
i think here is a little mistake, the correct expresion will be
If the arguments of the constructors clash with the member variables:
Mar 7 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: ali | last post by:
Hi, I'm trying to understand the reason for different output on the following codes Code1: #include <iostream.h> int main()
9
by: iceColdFire | last post by:
HI, I have a function as void f(int p) { return p++; } now I have created a function pointer as
20
by: __PPS__ | last post by:
Hello everybody in a quiz I had a question about dangling pointer: "What a dangling pointer is and the danger of using it" My answer was: "dangling pointer is a pointer that points to some...
67
by: Ike Naar | last post by:
Hi, Asking your advice on the following subject: Suppose I want to find out whether a given pointer (say, p) of type *T points to an element of a given array (say, a) of type T. A way to...
33
by: dough | last post by:
Is it possible in C to declare and initialize a pointer that points to itself? Why or why not?
1
by: Jeff | last post by:
I am struggling with the following How do I marshal/access a pointer to an array of strings within a structure Than Jef ----------------------------------------------------------------
16
by: Abhishek | last post by:
why do I see that in most C programs, pointers in functions are accepted as: int func(int i,(void *)p) where p is a pointer or an address which is passed from the place where it is called. what...
15
by: khan | last post by:
Hi, I read that pointer representation can non-zero bit pattern, machine specific.Compiler when comes accross value '0' in pointer context, converts it to machine specific null pointer...
6
by: lithiumcat | last post by:
Hi, maybe you remember me, some time ago I asked about how to store an integer value into a void*, and I learned that doing pointer arithmetic yeilding a pointer outside of an object (except the...
14
by: Szabolcs Borsanyi | last post by:
Deal all, The type typedef double ***tmp_tensor3; is meant to represent a three-dimensional array. For some reasons the standard array-of-array-of-array will not work in my case. Can I...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.