0

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
2
  • 4
    Don't use * characters to highlight code. That makes the code more confusing. Also, please post a minimal reproducible example Commented Jun 26, 2016 at 20:24
  • Why are you returning b += c.getBalance();? Value of b will only change in operator+= function scope (as b is passed by value, not by reference). I think that what you really want to do is return b + c.getBalance(); or perhaps pass b as reference double operator+=(double& b, const Account& c); and then increment it before returning b += c.getBalance(); return b. Commented Jun 26, 2016 at 20:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please repost with a minimum example rather than all your code :) It's now harder to read what your asking than *** highlight ***. ;)
ok just reposted, I was told to provide a working version earlier, I am still trying to get used to the format that is supposed to used to be posted. Thanks for the answer again it is much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.