C++ Class composition Question: How to set the private variables of a class that's within another class from the main ?

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  Bank 
{
public: 
const Account & getAccount(int) const; 

private:
Account accounts[10];
};


const Account & Bank::getAccount(int index) const
{ 
return accounts[index]; 
} 


The class Account has a private variable of type double called "balance" with it's own setters and getters.
Example:
1
2
3
4
5
6
7
8
9
class Account()
{
public:
double getBalance() const; 
double setBalance(double); 

private: 
double balance; 
};


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 ?

1
2
3
4
Account & Bank::getAccount(int index) 
{
return accounts[index]; 
}


It works for me but it doesn't seem like good coding practice.
Isn't there a better way to do 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.
Last edited on
Topic archived. No new replies allowed.