Magnahawk Magnahawk - 1 year ago 94
C++ Question

C++ Last object of my vector is overwriting every object

Here I am trying to create a vector of 5 SavingsAccount objects. Each SavingsAccount has a balance, which the user inputs. My problem is that when I print out the balance, the value of each balance equals whatever was entered last. For example, user inputs 100, 200, 300, etc, my program outputs all 500s instead of each entered balance.

I know there's probably a really simple explanation for this, but I seem to be running out of gas today. My guess is that when I call accounts.push_back, I'm assigning the same object to each element of the vector so that on the last run of the for loop, I'm assigning 5 objects with a balance of 500 into the vector.

If that's the case, I'm not entirely sure how to fix that. Any suggestions, or do I have another problem somewhere? Thanks in advance.

#include <iostream>
#include <iomanip>
#include <vector>
#include "SavingsAccount.h" // SavingsAccount class definition
using namespace std;

void initializeAccounts(vector<SavingsAccount> &, int);

int main()
//Number of accounts
const int NUM_OF_ACCOUNTS = 5;
//Create vector
vector <SavingsAccount> accounts(NUM_OF_ACCOUNTS);

//Initialize all 5 vectors with input from user
initializeAccounts(accounts, NUM_OF_ACCOUNTS);

//Print out the balances
for(int i = 0; i < NUM_OF_ACCOUNTS; i++)

void initializeAccounts(vector<SavingsAccount> &accounts, int accountSize)
double balance = 0;

for(int i = 0; i < accountSize; i++)
cout << "Please enter the balance for account " << i+1 << endl;
cin >> balance;


Answer Source

you already set the size of your vector with NUM_OF_ACCOUNTS elements:

vector <SavingsAccount> accounts(NUM_OF_ACCOUNTS);

So when you later push_back further elements in your initialize method, it adds to the already existing (empty elements)

BTW you pass the size of the vector whereas it is self-contained. But that's another story.

Simple fix: declare vector as empty at the start:

vector <SavingsAccount> accounts;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download