Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying a member variable

I’m having an issue with modifying a member of a class. I overloaded the operators and I think that I am calling the member correctly to modify it but am getting the issue that the "expression must be a modifiable l-value.
Any help would be appreciated
.h file

public:
    account& operator+= (float x);
    account& operator-= (float y);
    float set_balance();

.cpp file

   account& account::operator+=(float x)
    {
        this->acct_balance += x;
        return *this;
    }
    account& account::operator+=(float y)
    {
        this->acct_balance -= y;
        return *this;
    }
    float account::set_balance()
    {
        return this->acct_balance;
    }

main file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//deposit
        else if (imput == 2)
        {
            float deposit;
            cout << "Please enter the amount to deposit: ";
            cin >> deposit;
            user1.set_balance() += deposit;

        }
        //withdrawl
        else if (imput == 3)
        {
            float withdraw;
            cout << "Please enter the amount to deposit: ";
            cin >> withdraw;
            user1.set_balance() += withdraw; 

        }

>Solution :

Your set_balance function doesn’t set anything. You probably want this:

float& account::get_balance()
{
    return this->acct_balance;
}

Then you can do user1.get_balance() += withdraw;.

This get_balance function gets the balance as a modifiable l-value, which is what you need.

Since you have an operator+=, you could also just do user1 += withdraw;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading