The class "Bank" has within it an array of objects of type "Account". The bank class has a getter function for the array of accounts that returns single object of that array. Example:
How do I set the balance from the main when the main only has an Object of type bank ? Each class has a respective setter and getter for all variables. What the appropriate way to do this?
Example of a main that's giving me troubles
1 2 3 4 5 6 7 8 9 10 11 12 13
int main ()
{
Bank abank;
int index;
double balance;
cin>>index;
cin>>balance;
abank.getAccount(index-1).setBalance(balance);
return 0;
}
This is giving me troubles because getAccount() returns a const so it can't be modified. Should I just remove the const like this ?
Returning a mutable reference is basically how the operator[] is implemented for standard containers like vectors.
You may want to provide an overload for this function which should return a const reference, in the case that the 'Bank' object is const-qualified, though that doesn't seem likely to occur in your code.
In your case it's safe to do this since the 'accounts' array is bound to the lifetime of the 'Bank' object which contains it. It wouldn't be safe to return a reference to a local variable which goes out of scope as soon as the function terminates.