question about array of class objects

what do i need to change in the class so that ill be able to declare an array without gettin error notification?
this way i get an error:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string>
#include <cstring>

using namespace std;
class Employee {

	char name[21];
	unsigned int salary;
	
public:
	Employee();
	Employee(string,unsigned int);
	void init(string, unsigned int);
	void print();
	Employee operator + (Employee);
};

Employee::Employee(){
	name[20]=0;
}
Employee::Employee(string iname, unsigned int salary)
{
	strncpy_s (name,iname.c_str(),20);
	this->salary=salary;
}

    void Employee::init(string iname, unsigned int salary)
{
	strncpy_s (name,iname.c_str(),20);
	this->salary=salary;
}

void Employee::print()
{
	cout<<"Employee name: "<<name<<endl;
	cout<<"Employee salary: "<<salary<<endl;
}


int main()
{
	Employee emparr[2];
	emparr[0].init("al sade",57000);
	emparr[1].init("guy ger", 89000);
	emparr[2].init("martine", 54000);

	for (int i=0;i<3;i++)
		emparr[i].print();


	
}


Array elements start at 0 and go to Array Size - 1. You are trying to access "emparr[2]" which will cause undefined behavior.

If you get any other errors after that make sure to show what they are.
i changed the array size and it works thx! but still, why does the last one (emparr[2]) is Inaccessible?? is it like a null terminated element ?
No I wouldn't say it's null terminated, it is just because C++ uses zero based indexing. You define an array of size 2 so it gives you element 0 and element 1, it would be strange for it to give you any more after that.

There are lots of online sources about why arrays start at 0 if you want to look into that.
Topic archived. No new replies allowed.