= overloading

I have a complex no class. I am trying to overload =.
I have pasted some code below

Q1. usually an = returns true or false if the assignment was successful or not
Is the code written below correct for such an overloading.
if it is not, what is the problem there.
Q2. = is recommended to be written as a class member. Can i however, write it as a non class function? How ?


bool CmplxNo::operator= (const CmplxNo& a)
{
try
{
this->re = a.re;
this->im = a.im;
return true;
}
catch
{
return false;
}
}
Last edited on
Operator= should not return a bool. It should return the lhs, to allow chaining. In the case of this function, you would return *this;

I suppose you could write it as a global function. The first parameter is the lhs, and the second is the rhs.
No, the assignment operator must be a member function.
if the assignement operator must be a member function, how do i make it return a boolean value to check if the assignment has been done ??

Like I said, it shouldn't return a bool. It should return a reference to the object that called it. If the assignment fails, I guess you would need to throw an exception. Using a boolean return value is not recommended.
Like I said, it shouldn't return a bool. It should return a reference to the object that called it. If the assignment fails, I guess you would need to throw an exception. Using a boolean return value is not recommended.
if the assignement operator must be a member function, how do i make it return a boolean value to check if the assignment has been done ??


You shouldn't

Assignments should never fail. Or if they do, they should probably throw an exception.

If you had to check to make sure every assignment worked OK, your code would be hell.
You want to return a *CmplxNo.

That's the class you're assigning something to, right?
Last edited on
Do it the way the standard streams do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Fooey
  {
  public:
    // assignments
    Fooey& operator = ( ... )
      {
      ...
      return *this;
      }

    // boolean status: is the object in a valid/useful state?
    operator const void* ()
      {
      if (ok) return this;
      else return NULL;
      }
  };

Hope this helps.
Topic archived. No new replies allowed.