Search code examples
c++classoperator-overloadingreturn-typeassignment-operator

Why do I get errors when I use the overloaded assignment operator, but I don't get using the compiler-supplied one?


I tried my best to only put the most important parts:

header.h

#include <cstdint>
#include <string>
#include <vector>
#include "byte.h" /// doesn't matter what's in here
#pragma once

using int64 = int64_t;
using int32 = int32_t;

/// FORWARD-DECLARATIONS
class BigInt;

/// *** CLASS BIGINT ***

class BigInt
{
    std::vector<byte> vec;
    bool neg; /// true if negative

public:
    /// CONSTRUCTORS
    BigInt ();
    BigInt (const int64);

    /// OPERATORS
    /// ASSIGNMENT
    void operator = (const BigInt&);

    /// ARITHMETIC
    BigInt operator + (const BigInt&);
    BigInt operator - (const BigInt&);
};

/// DEFINITIONS
/// CONSTRUCTORS
BigInt::BigInt () : vec(1), neg(0) {}
BigInt::BigInt (const int64 x) : vec(x), neg(0) {}

/// OPERATORS
/// ASSIGNMENT
void BigInt::operator = (const BigInt &p)
{
    (*this).vec = p.vec;
    (*this).neg = p.neg;
}

/// ARITHMETIC
BigInt BigInt::operator + (const BigInt &p)
{
    BigInt a = *this;
    BigInt b = p;
    BigInt res;

    if (a.neg ^ b.neg)
    {
        if (a.neg)
            std::swap(a, b);
        b.neg = 0;
        /*return*/ res = a.BigInt::operator - (b); /// I get an error if I don't comment this out
        return res;
    }

    return res;
}

BigInt BigInt::operator - (const BigInt &p)
{
    BigInt a = *this;
    BigInt b = p;
    BigInt res;

    return res;
}

In BigInt BigInt::operator + (const BigInt &p) I get an error when I try to return return res = a.BigInt::operator - (b);, but not when I return it like this: res = a.BigInt::operator - (b); return res;. But this only happens when I overload the = operator, it doesn't happen with the compiler supplied one.

ERROR: no viable conversion from returned value of type 'void' to function return type 'BigInt' return res = a.BigInt::operator - (b);


Solution

  • Your operator= returns void, which can't be returned in return res = a.BigInt::operator - (b);, as the error message said, operator + is supposed to return a BigInt.

    You should declare operator= as returning BigInt& (as the one generated by compiler does).

    BigInt& BigInt::operator = (const BigInt &p)
    {
        (*this).vec = p.vec;
        (*this).neg = p.neg;
        return *this;
    }