Nicholas
Nicholas

Reputation: 2668

How do I use C++ keyword "this" along with member function "operator="?

The question stems from cplusplus. A class that represents a two-dimensional vector is defined as below,

class CVector {
  public:
    int x,y;
    CVector () {}
    CVector (int a, int b) : x(a), y(b) {}
    CVector& operator = (const CVector&);
};

CVector& CVector::operator= (const CVector& param)
{
  x=param.x;
  y=param.y;
  return *this;
}

My question is how do I use operator =? For example,

CVector a, b;
b.x = 1;
b.y = 3;
CVector & c = a = b;

My confusion now is that suppose there are two CVector objects a and b, and if I execute c=a=b(equivalently to c=a.operator=(b)), then is it true that two things are done here: first, a have the same x and y as b; second, c is set as an alias/reference of a? I would appreciate any examples.

Upvotes: 0

Views: 65

Answers (1)

David Haim
David Haim

Reputation: 26476

It really depends on how did you declare c.

if c is just CVector, then the expression

a=b;

returns CVector&. then, since c is a full fledged object and not a reference, the compiler is looking for the method XXX operator = (CVector&).

now, CVector doesn't have any XXX operator = (CVector&) method (note that the method gets a reference, not a const reference), but is has CVector& operator = (const CVector&) (a method which gets const reference).

is the casting between reference to const reference is allowed? yes, so the method CVector& operator = (const CVector&) will be called.

now, c has the values of a and b. again, c is an object.

now, if you declared c as CVector& or const CVector& (a reference), then the expression

CVector& c = a = b;

will alias c as a, because you assigned the reference returned by a.operator =(b) to yet another reference.

to sum things up, there is a difference between CVector c = a = b;
and CVector& c = a = b; , the first will "copy" the data of a to a real object c while the last will alias c as a.

Upvotes: 1

Related Questions