I am learning c++ and having hard time on this exercise of my internet course. It takes data from user through constructer and print it. However, the destructor function is called immediately after every time i enter value.
class employee{
private:
int no;
char *name;
char *position;
float time;
public:
employee();
employee(int a, char *n, char *m, float x);
~employee();
//setter
void setNo(int);
void setName(char*);
void setPos(char*);
void setTime(float);
//getter
int getNo();
char* getName();
char* getPos();
float getTime();
};
void employee::setNo(int a){
no = a;
}
void employee::setName(char* a){
delete name;
name = new char[strlen(a) + 1];
strcpy(name, a);
}
void employee::setPos(char* a){
delete position;
position = new char[strlen(a) + 1];
strcpy(position, a);
}
void employee::setTime(float a){
if(a > 0 && a > 150){
cout<<"Enter valid time! (The restriction range is between 0 to 150.)"<<endl;
exit(0);
}
else{
time = a;
}
}
//getter
int employee::getNo(){
return no;
}
char* employee::getName(){
return name;
}
char* employee::getPos(){
return position;
}
float employee::getTime(){
return time;
}
//constructer
employee::employee(){
name = new char[1];
position = new char[8];
no = 0;
strcpy(name, " ");
strcpy(position, "employee");
time;
}
employee::employee(int a, char *n, char *m, float x){
name = new char[strlen(n) + 1];
position = new char[strlen(m) + 1];
no = a;
strcpy(name, n);
strcpy(position, m);
time = x;
}
employee::~employee(){
cout<<"The object "<<position<<" "<<name<<" is deleted."<<endl;
delete(name);
delete(position);
}
int main(){
int n;
cout<<"The number of employees: ";
cin>>n;
employee *a = new employee;
for(int i = 0; i < n; i++){
int no;
float time;
char name[20], position[10];
cout<<"Enter No: ";
cin>>no;
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Position: ";
cin>>position;
cout<<"Enter Time: ";
cin>>time;
a[i] = employee(no, name, position, time);
}
}
Maybe I am expecting something wrong. What i want is the destructor to be called and print msg about objects were deleted, after entering data all my datas. But the destructor is called right after the first employers data insertion, and same goes other employers.