a-one
a-one

Reputation: 103

operator return value issue

I am having an issue with a return value with a += operator.

the following is the specific code that is related. If more code needs to be shown I will provide it:

    double operator+=(double b, const Account& c)
    {
      return b += c.getBalance();
    }

where it is implemented in the main:

    for(int i = 0; i < NUMBER_OF_ACCOUNTS; i++)
    {
        std::cout << i+1 << "- " << (balance += *AC[i]) << std::endl;
    }
    std::cout << "Total Balance: " << balance << std::endl;

output I am receiving:

1- 10302.98
2- 10302.98
3- 201.00
Total Balance: 0.00

output I am trying to get:

1- 10302.98
2- 20605.96
3- 20806.96
Total Balance: 20806.96

Upvotes: 0

Views: 74

Answers (1)

izaak_pyzaak
izaak_pyzaak

Reputation: 960

You need to pass in b by reference:

double operator+=(double &b, const Account& c)
{
  return b += c.getBalance();
}

instead of

double operator+=(double b, const Account& c)
{
  return b += c.getBalance();
}

Otherwise, think about what happens, the value of balance(0) is copied in with every call, rather than you actually summing to the memory location aliased by balance.

Upvotes: 1

Related Questions