user1198783
user1198783

Reputation: 47

Operator = function and an add function cant seem to coexist

I'm having an issue with two of my functions. I have an operator = method as well as an add method. They work fine on their own, as in I can only use one or the other during one compile. For example I need to comment out the add function in order for the operator = method to work and vice versa. The errors I'm getting 10 no match for 'operator=' in 'c = (&a)->HUGE_INT::add(((HUGE_INT&)(&b)))'

     HUGE_INT HUGE_INT::operator=(HUGE_INT &orig)
        {
        //code
         return *this;
        }

        HUGE_INT HUGE_INT::add(HUGE_INT &a)
        {
         //code
         return object;
        }

//client
    HUGE_INT a(9999999),b(1111),c,d;
       c = a.add(b);
       d = a;

Upvotes: 1

Views: 175

Answers (3)

Yuushi
Yuushi

Reputation: 26080

Your operator= should be returning a reference as well as taking a const reference; that is, it should have a signature HUGE_INT& HUGE_INT::operator=(const HUGE_INT& orig).

As a side note, it's really bad C++ style to use all caps for class names. All capitals are generally reserved for macros.

Upvotes: 1

Lefteris
Lefteris

Reputation: 3256

I fixed the code for you, ofcourse it does nothing now as in your example but it compiles. The reason is that you need to specify the argument of the '=' operator as constant and as stated by the other posters you should also return a reference to the object.

class HUGE_INT
{
public:
HUGE_INT(){this->var = 0;}
HUGE_INT(int v){this->var = v;};

HUGE_INT& operator=(const HUGE_INT &orig)
{

 return *this;
}

HUGE_INT add(HUGE_INT &a)
{
    HUGE_INT object;
 return object;
}

private:
    int var;
};


int main()
{


//client
HUGE_INT a(9999999),b(1111),c,d;
   c = a.add(b);
   d = a;
}

To get a better understanding check out atutorial on operator overloading

Upvotes: 1

Mankarse
Mankarse

Reputation: 40633

The problem that you are having is that you are returning by value from add, and taking the argument to operator= by non-const reference.

The temporary object returned from add is an rvalue, and so it cannot be bound to a non-const reference.

Unless you are doing something very strange, you probably want to change operator= to take its argument by reference to const:

    HUGE_INT& HUGE_INT::operator=(HUGE_INT const& orig)
    {
    //code
     return *this;
    }

(I also changed it to return by reference, as this is the standard signature for operator=.)

Upvotes: 5

Related Questions