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
             int num, den;
           //other stuff

    ratio& ratio::operator=(const ratio& r)
    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;


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


    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;

    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook