C++ *this pointer

Discussion in 'OT Technology' started by adam17, Feb 1, 2005.

  1. adam17

    adam17 now im gonna sing the doom song! doom doom doom do

    Joined:
    Aug 25, 2004
    Messages:
    1,666
    Likes Received:
    0
    Location:
    n ur gf's bed
    can anybody point me to a good place for a tutorial on the *this pointer in C++? im having some issues with my code and i know the only solution is to use the this pointer. i just need to figure out how to use it and implement it
     
  2. skinjob

    skinjob Active Member

    Joined:
    Jan 6, 2001
    Messages:
    2,337
    Likes Received:
    0
    Location:
    Aztlán
    No need to implement it, since it's automatically implemented for every class instance. You can think of the this pointer as a private const data member that's initialized to point to the class instance that the member belongs to.

    Code:
    class Foo
    {
    public:
    	 int m_data;
     
    	 void memberfunc()
    	 {
    		   this->m_data = 1;
    		   // is exactly the same as
    		   m_data = 1;
    	 }
    };
    
    *this is useful for example, when inside a member function, you need to refer to the current instance if you want to pass a pointer to it to a function outside the class scope.

    Post some details about the issue you're trying to work out if you need some help.
     
  3. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    Also, if you have a local variable and an instance variable with the same name, you can use this to access the instance version from within the scope of the local one:

    Code:
    class Foo
    {
    public:
    int m_data;
    void memberfunc()
    {
    int m_data;
    // the public m_data
    this->m_data = 100;
    // the m_data we just declared
    m_data = 1;
    // 100
    cout << this->m_data << endl;
    // 1
    cout << m_data << endl;
    }
    };
     
  4. adam17

    adam17 now im gonna sing the doom song! doom doom doom do

    Joined:
    Aug 25, 2004
    Messages:
    1,666
    Likes Received:
    0
    Location:
    n ur gf's bed
    thanks alot!!! it makes sooo much more since now.
     

Share This Page