amadeus
amadeus

Reputation: 69

OVERLOADING OPERATORS = error

I am trying to use overloading concept to equate 3 objects c1, c2, c3. But it is giving me an error

error: no match for 'operator=' in 'c3 = c2. circle::operator=(((circle&)(& c1)))'

What's the reason behind it how do I rectify it??

#include<iostream>
using namespace std;

class circle
{
  private:
    int radius;
    float x,y;
  public:
    circle()
    {}
    circle(int rr,float xx,float yy)
    {
      radius=rr;
      x=xx;
      y=yy;
    }
    circle& operator=(const circle& c)
    {
     cout<<endl<<"assignment operator invoked";  
     radius=c.radius;
     x=c.x;
     y=c.y;
     return *this;
     }
    void showdata()
    {
      cout<<endl<<"\n radius="<<radius;
      cout<<endl<<"x coordinate="<<x;
      cout<<endl<<"y coordinate="<<y<<endl;
    }
};
int main()
{
  circle c1 (10,2.5,2.5);
  circle c2,c3;
  c3=c2=c1;
  c1.showdata();
  c2.showdata();
  c3.showdata();
  return 0;
} 

so this overloaded operator will be called two times.. First for c2=c1 and then for c3=c2 but how will compiler compare it with overloaded operator definition??

Upvotes: 1

Views: 126

Answers (1)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

In order to chain operator= calls, you must make sure that it returns a reference

circle& operator=(const circle& c)
{
   cout<<endl<<"assignment operator invoked";  
   radius=c.radius;
   x=c.x;
   y=c.y;
   return *this;
}

c1=c2=c3 is parsed as c1 = (c2 = c3). If operator = doesn't return a reference, c2 = c3 is an rvalue, and it cannot bind to the reference argument of c1.operator = (In case if the argument is a reference to const, it can bind to rvalues, but that doesn't mean you shouldn't return a reference).

Also note that it makes sense to take the parameter by const reference, because you don't want to change the argument that you assign.

Also remember the rule of three, that is, if you really need to do any of the following:

  • overload operator =

  • explicitly provide a copy constructor

  • explicitly provide a destructor

then you probably want to do the other two too. In your particular case, you don't seem to need to overload operator = at all.

Upvotes: 6

Related Questions