A dynamic array objects in a class

Feb 21, 2014 at 3:51pm
I'm designing a program that mimics a small banking program. There's two classes I'm trying to design right now, which is the transaction class and the account class. I need the account class to contain an array of transaction objects, but I need it to be sized dynamically as the account performs more transactions. Is there a way to dynamically size an array of objects in a class, and if so, what would be the method to doing that?

EDIT: The requirements state that I CANNOT utilize the STL/vectors.
Last edited on Feb 21, 2014 at 4:27pm
Feb 21, 2014 at 4:07pm
Use std::vector.
http://www.cplusplus.com/reference/vector/vector/

It would be something like
1
2
3
4
5
6
7
8
9
class Transaction
{
    // ...
};
class Account
{
    std::vector<Transaction> transactions;
    // ...
};

To add a transaction, it would simply be transactions.push_back(someTransaction);
Feb 21, 2014 at 4:16pm
But here's the caveat, and I should have specified this before. The requirements state that I CANNOT utilize the STL/vectors. Otherwise, I would have banged this out days ago.
Last edited on Feb 21, 2014 at 4:16pm
Feb 21, 2014 at 4:32pm
Okay, then you'll have to do it yourself manually....

1
2
3
4
5
6
7
8
9
10
11
12
class Account
{
    Transaction* transactions;
    // ...
    public:
        Account(): transactions(new Transaction[/* some default size */]) {}
        // Rule of 3
        Account(const Account& other);
        ~Account() { delete[] transactions; }
        Account& operator=(const Account& other);
        // ...
};

To resize, you'll have to create a new (bigger) array, copy/move all of the elements in the old array to the new one, destroy the old array, and set the pointer to the array to point to the new array.
So something like
1
2
3
4
5
6
7
8
9
void Account::resize(int newSize)
{
    Transaction* newArray = new Transaction[newSize];
    // Copy everything over
    for (int i = 0; i < /* old size -- probably need an extra member variable for that*/; ++i)
        newArray[i] = transactions[i];
    delete[] transactions;
    transactions = newArray;
}
Topic archived. No new replies allowed.