This pointer

  • #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:
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?
 

Answers and Replies

  • #2
Dale
Mentor
Insights Author
2020 Award
31,495
8,212
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)
 
  • #3
Thank you. That really clears it up. It also makes the multiple assignment thing easier to understand.
 

Related Threads on This pointer

  • Last Post
2
Replies
40
Views
824
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
16
Views
3K
Replies
12
Views
361
Replies
2
Views
4K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
13
Views
2K
  • Last Post
Replies
7
Views
4K
Top