Tugal.44
Tugal.44

Reputation: 153

expression must be a modifiable lvalue in my class

I know what it means but in my situation I don't understand why my IDE yelling me about this.

Rational operator*(const Rational& that1, const Rational& that2)
{
    Rational temp(that1);
    temp.getNom() *= that2.getNom();
    temp.getDenom() *= that2.getDenom();
    return temp;
}

int Rational::getNom() const
{
    return m_iNom / gcd(m_iNom, m_iDenom);
}
int Rational::getDenom() const
{
    return m_iDenom / gcd(m_iNom, m_iDenom);
}

float Rational::gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

m_iNom & m_iDenom are private data members inside Rational class.

I'm getting 'expression must be a modifiable lvalue' at :

temp.getNom() *= that2.getNom();
temp.getDenom() *= that2.getDenom();

Upvotes: 0

Views: 5395

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

As the compiler says, you can't assign to the return value.
Even if you could assign to the return value, the member variables would be unaffected — the accessors return the values of the member variables, not the actual variables.

The idiomatic way of doing this is to first implement operator *= as a member:

Rational& operator *= (const Rational& that)
{
    m_iNom *= that.m_iNom;
    m_iDenom *= that.m_iDenom;
    return *this;
}

and then use that to implement *:

Rational operator*(const Rational& that1, const Rational& that2)
{
    Rational result(that1);
    result *= that2;
    return result;
}

Upvotes: 1

Nicolas Albert
Nicolas Albert

Reputation: 2596

You cannot affect a value to a function or method return.

temp.getNom() *= that2.getNom(); is like temp.getNom() = temp.getNom() * that2.getNom();

It's like to write 2 = 2 * 3 and set 2 = 5 … no sense!

Upvotes: 1

Related Questions