This pointer

This is a discussion on This pointer within the C++ Programming forums, part of the General Programming Boards category; I am working with Teach Yourself C++ in 21 Days and am attempting to self-teach. I am trying to grasp ...

  1. #1
    Unregistered
    Guest

    This pointer

    I am working with Teach Yourself C++ in 21 Days and am attempting to self-teach. I am trying to grasp the this pointer and when to use it. Anyone who is willing to explain this to me please do. Thank you in advance.

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,670
    Not totally sure on the exact syntax, but basically you are implicitly returning a pointer to the structure at hand. It's limited to non-static member functions.

    class foo:ublic bar{ long ID;};

    foo::BoundsCheck{
    if( this->ID <=1010101)
    return *this;
    return NULL;
    }

    Not so sure that'd compile but you get the idea.



    ITSA
    Socket Library!

  3. #3
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Use it when you want to return the current object, or see if a passed object is the same object as the reciever of the message. For example, if you were to write your own comparsion operation for a class, it might look like this.
    Code:
    class Foo {
    public:
         bool equals(const Foo& other);
         // other stuff
    private:
         char bigString[1024];
    };
    
    bool Foo::equals(const Foo& other) {
           if (this == &other) { // compare pointers, if they are at same location, they are obviously same object, and can avoid costly bigString compare
                     return true;
           }
           return strcmp(bigString, other.bigString) == 0;
    }
    The this pointer isn't used explicitly all that much, however.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21