Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Overloading operator=

Okay so I have a class that has 'weak typing' I.E. it can store many different types defined as:

#include <string>

class myObject{
   public:
      bool isString;
      std::string strVal;

      bool isNumber;
      double numVal;

      bool isBoolean;
      bool boolVal;

      double operator= (const myObject &);
};

I would like to overload the assignment operator like this:

double myObject::operator= (const myObject &right){
   if(right.isNumber){
      return right.numVal;
   }else{
      // Arbitrary Throw.
      throw 5;
   }
}

So that I can do this:

int main(){
   myObject obj;
   obj.isNumber = true;
   obj.numVal = 17.5;
   //This is what I would like to do
   double number = obj;
}

But when I do that, I get:

error: cannot convert ‘myObject’ to ‘double’ in initialization 

At the assignment.

I have also tried:

int main(){
   myObject obj;
   obj.isNumber = true;
   obj.numVal = 17.5;
   //This is what I would like to do
   double number;
   number = obj;
}

To which I get:

error: cannot convert ‘myObject’ to ‘double’ in assignment

Is there something I am missing? or is it simply not possible to do a conversion like that by overloading operator=.

like image 426
zmbush Avatar asked Jan 15 '10 22:01

zmbush


1 Answers

Overloading operator= changes the behaviour when assigning to objects of your class type.

If you want to provide implicit conversion to other types you need to supply a conversion operator, e.g.

operator double() const
{
    if (!isNumber)
        throw something();
    return numVal;
}
like image 59
CB Bailey Avatar answered Oct 02 '22 16:10

CB Bailey