How to Create an array of objects?

How to Create an array of objects like this?

1
2
3
4
5
6
7
8
9
10
11
 class student{
private:
	string name;
	int x, y;  // (x , y Axis) Student Location in class
public:
	student(int a,int b,string c) {
   a=x;
   b=y;
   c=name;
	}
};




1
2
3
4
5
int main(){
student a[20]; // wrong 
student a[20](1,2,"Mary"); //wrong

}


I want to Create constructor for each 20 students.
1
2
 
student a[20];


each constructor(student) input (xAxis, yAxis, name)

For example,

In a[0], student 1 ,I want to input a[0](1,2,"Mary")
In a[1], student 2 ,I want to input a[1](1,3,"Tom")

How can I improve it?
Last edited on
student a[20]; // wrong
Which constructor will be called and with which parameters for those 20 objects? Do you have this constructor in your class?

student a[20](1,2,"Mary"); //wrong
You need to provide initializer for all array elements if your class lacks default constructor:
student a[3] {{1,2,"Mary"}, {1,2,"Mary"}, {1,2,"Mary"}}
Fast answer
Make a default constructor

1
2
3
4
5
6
student() : x(0) , y(0) , name()  // class members initialization
{

}

student a[20]; // This will work now 



Also read more about classes , constructors and class members initialization
http://www.cplusplus.com/doc/tutorial/classes/
Thank and sorry, I forgot to talk about my goal.

I want to Create constructor for each 20 students.
1
2
 
student a[20];


each constructor(student) input (xAxis, yAxis, name)

For example,

In a[0], student 1 ,I want to input a[0](1,2,"Mary")
In a[1], student 2 ,I want to input a[1](1,3,"Tom")
Last edited on
In array all objects are constructed in time of array declaration.

That means you either should provide 20 initializers for your array (see exampe with 3 in my post earlier) or provide a default constructor and assign other values later.

You might consider using vector instead. It gows dinamically, does not require construction of elements which are not yet created, knows his size and generally better.
Topic archived. No new replies allowed.