Member Avatar for slanker70

Basically, my proggramme is

CLASS ACCOUNT DEFINITION

class Account
{
public:
    Account();
    void setBalance(int);
    void getBalance();
private:
    int balance;
}

CLASS ACCOUNT IMPLEMENTATION

#include <iostream>
#include "account.h"
using namespace std;
Account::Account()
{
}
void Account::getBalance()
{
    cout << balance;
}
void Account::setBalance(int ammount)
{
    balance = ammount;
}

MAIN

#include <iostream>
#include "account.h"
using namespace std;
int main()
{
    Account obj[10];
    int flag = 0;
    int id;
    int ammount;
    char more;
    while(flag == 0)
    {
        Account acc;
        cout << "Enter account number: ";
        cin >> id;
        cout << "Enter ammount: ";
        cin >> ammount;
        acc.setBalance(ammount);
        obj[id] = acc;
        cout << "Create more? (y/n)";
        cin >> more;
        if (more == 'n')
        {
            flag = 1;
        }
    }
    return 0;
}

The problem is, it can only create an array of 10 account objects. How can I use dynamic memory so it can create an undefined array of account objects. Please assist me.

Thank you

Member Avatar for iamthwee

Why not use a vector?

Member Avatar for slanker70

Hi,

Thank you for the quick reply, i'm currently on the process of learning c++ and specially dynamnic memory in this case. Most of the examples that I could find does not relate to using dynamic memory on an aray of objects.

Thank you

Accept the size of the Account array from the user at run time and dynamically allocate the array. If not that, then use vectors.

Account* accArray = new Account[size_from_user];
for(int i = 0; i < size_from_user; ++i)
{
//code
}
delete[] accArray;
Member Avatar for slanker70

HI,

Thank you for the reply, but can actually show me how to implement that to an array of objects, as I say all the of the examples on dynamic memory is for an array of int, char but none for an array of objects.

Cheers.

Read the sample snippet I posted in my previous post.

Member Avatar for iamthwee

An array of objects should be handled in a similar fashion to an array of ints or strings for that matter.

An array of objects should be handled in a similar fashion to an array of ints or strings for that matter.

this is possible only if there is an accessible default constructor.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.