1

for example, in this one, I 'm not very understand about the this pointer, this question is not about operator+ overload, is about the this pointer, and its relation between the class,

*this pointer point to what thing?

thank u very much!

 class Integer {
        int i;
    public:
        Integer(int ii): i(ii) { }
        const Integer operator+(const Integer& rv) const {
            cout<<"operator+"<<endl;
        }

        Integer&
            operator+=(const Integer& rv) {
                i += rv.i;
                return *this;
        }

    }
user1279988
  • 757
  • 1
  • 11
  • 27
  • 1
    What good C++ programming book did you read? It is difficult to explain in a few minutes what an entire book is giving you. – Basile Starynkevitch Apr 07 '12 at 10:03
  • thinking in c++, I want figure out some thing I often is no very clear when I reading this book. Also that's where my most question come from – user1279988 Apr 07 '12 at 10:05
  • 1
    What should be the "thing" you would like to figure out? Maybe this additional information would help us telling you the proper part of info about "this". – dexametason Apr 07 '12 at 10:07
  • thank u for your reminder, "dexametason", I will. I want to know something about "this" pointer, and somebody below "Jon" give some clues. – user1279988 Apr 07 '12 at 10:15

2 Answers2

3

operator+= needs to return a reference to the current object (after it has been incremented) so that you can still write code such as

// UGLY CODE, ONLY TO ILLUSTRATE A POINT
Integer x, y;
x = (y += 10) + 1;

This form of the operator (taking a const reference, returning a reference) is also called the canonical form.

Where do you get the reference to return? You have this, which points to the current object, but you cannot return a pointer. So you dereference the pointer with operator* and return the result:

return *this;
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
3

thisidentifies a special type of pointer.IF you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it. Basically this pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.

aquasan
  • 374
  • 3
  • 7