First of all, thanks for any help that I'll receive.
Now on to the question.

I'm wondering how do I create an array of an object in C++?

I've done this in Java before but I've got no idea how to do it in C++.

import Accout.java

private Account accounts[];

public AccountDatabase()
{
accounts = new Account[ 2 ];
accounts[ 0 ] = new Account(12345, 54321, 1000.00);
}

I'm trying to convert that exact same thing from Java to C++.

Edited 6 Years Ago by rlhh: n/a

I think what you need is structs.
Here is an example:

//usual intro stuff
#include <cstdlib>
#include <iostream>
using namespace std;

//create a struct for our account type
struct account{
        //this is where initialize the data variables for an account
        //acount number
	int number;
	//balance
	float amount;
	} ;

//usual main
int main(){
        //create an array of type "account"
        //size 20, for example
	account acc_list[20];
	//set the number and amount value for the first account
	//remember that account one is at position 0 in the array
	acc_list[0].number = 123456;
	acc_list[0].amount = 312.48;

        //repeat for the second acount (position 1 in the array)
	acc_list[1].number = 98765;
	acc_list[1].amount = 234.22;
	
	//print out to test
	//i only used the dollar sign because the pound sign won't
	//show properly...grrrrrrrr...
	cout<<"Account 1:           $"<<acc_list[0].amount<<endl;
	cout<<"Account 2:           $"<<acc_list[1].amount<<endl;
	
	//pause so we can see the result
	//only for windows/DOS
	system("pause");
	}

And here's a link to a tut an better explanation:
http://www.cplusplus.com/doc/tutorial/structures/

Please upvote/solved if this helped/solved your problem :)

Edited 6 Years Ago by SgtMe: n/a

that is one way of doing it. But in the example (by SgtMes)you are not handling objects. Here is how you can do this.

class hello
{
.
.
.
}

main()
{
hello *ha[5];

ha[0] = new hello(any parameters you declare);
ha[0]->method1()
ha[1] = new hello(any parameters you declare);
ha[1]->method1()
.
.
.
ha[n] = new hello(any parameters you declare);
ha[n]->method1()

}

I guess your not handling objects as such, but for doing accounts and database style things, I guess a struct would be slightly simpler than a class. Just my opinion though :)

hmmm, that might be true. But the query was about handling objects in an array so I had to point out. so no worries.

Hmm, I think that both of the methods stated above are useful. I'll do more research from the details that you guys have given me. Thanks. :D

This question has already been answered. Start a new discussion instead.