Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

This pointer

  1. Jul 17, 2008 #1
    I've got a doubt regarding the this pointer. Im using schaums outlines programming with c++. In operator overloading (Chapter 11 p257), when you overload the assignment operator (=), the code looks something like this:

    Code (Text):

    class ratio
    {  public:
             //constructor and copy constructor definition
             ratio& operator=(const ratio&); //overloading assignment operator
        private:
             int num, den;
           //other stuff
    };

    ratio& ratio::operator=(const ratio& r)
    {
       num=r.num;
       den=r.den;
    return *this;
    }

     
    The problem is that I find the language ambiguous. It says:
    'The return type is a reference to an object of the same class, but then this means that the function should return the object that is being assigned in order for the assignment chain to work, so when the assignment operator is being overloaded as a class member function, it should return the object that owns the call.'

    Which object owns the call? If you have say,

    ratio a,b;

    a=b;

    does a own the call or does b?
     
  2. jcsd
  3. Jul 17, 2008 #2

    Dale

    Staff: Mentor

    Inside the operator= function call the this pointer is a pointer to the object on the left-hand side of the = sign (so a in your example). The left-hand side is also the type of object that gets the call. I.e.

    ratio a;
    specialratio b;
    a=b;

    would call ratio& ratio::eek:perator=(const specialratio& r) and not specialratio& specialratio::eek:perator=(const ratio& r)
     
  4. Jul 17, 2008 #3
    Thank you. That really clears it up. It also makes the multiple assignment thing easier to understand.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: This pointer
  1. Pointer confusion (Replies: 1)

  2. Pointer question (Replies: 2)

  3. Pointers and classes (Replies: 1)

  4. Use of pointers (Replies: 3)

  5. Pointers and strings (Replies: 19)

Loading...