Let's say I have the following code:
#include <iostream> using namespace std; class Account { private: float balance; public: Account() { balance = 0.0; }; float GetBalance() { return balance; }; void SetBalance(float newBalance) { balance = newBalance; }; }; Account mainAccount; Account& GetAccount() { return mainAccount; } void PrintAccountInfo() { cout << "mainAccount balance is " << mainAccount.GetBalance() << endl; } int main() { PrintAccountInfo(); Account &a = GetAccount(); // Line 31 a.SetBalance(30.0); PrintAccountInfo(); return 0; }
When I run it, I get the following output (as expected):
mainAccount balance is 0 mainAccount balance is 30
However, on line 31, if I select "&" in "Account & a" to do it like this:
Account a = GetAccount(); // note lack of "&"
I get this output:
mainAccount balance is 0 mainAccount balance is 0
How did it happen? I thought returning the link, "&" is redundant / optional? I basically misunderstand how links work in C ++?
EDIT: Thanks, now I understand why they are different. However, then I should not do this:
Account GetAccount() { return mainAccount; } int main() { Account &a = GetAccount();
However, when I run this, I get an error:
untitled: In the function 'int main ():
untitled: 31: error: invalid initialization of a non-constant link of type 'Account & from the temporary type' Account
source share