This program compilation succeeded but it doesn't work. I guess it has something to do with the assignment operator or the copy constructor but I can't figure out what...
Header:
class employee{
char *name;
unsigned int salary;
public:
employee();
employee(const char*);
employee(const char*,unsigned int);
employee (const employee&);
employee operator = (employee);
void init(const char*,unsigned int);
void print();
~employee();
};
Cpp:
#include <iostream>
#include <string>
#include "class.h"
using namespace std;
employee::employee() : salary(1000)
{
name=new char[20];
}
employee::employee(const char* ename) : salary(1000)
{
strcpy_s(name,20,ename);
}
employee::employee(const char* ename,unsigned int salary)
{
name=new char[20];
strcpy_s(name,20,ename);
this->salary=salary;
}
employee::employee(const employee& emp)
{
name=new char[20];
int i=0;
while (name[i]!='\0')
{
name[i]=emp.name[i];
i++;
}
salary=emp.salary;
}
void employee::init(const char* ename, unsigned int salary)
{
name=new char[20];
strcpy_s(name,20,ename);
this->salary=salary;
}
void employee::print()
{
cout<<"name: ";
int i=0;
while (name[i]!='\0')
{
cout<<name[i];
i++;
}
cout<<"\n"<<"salary: "<<salary<<endl;
}
employee employee::operator = (employee emp)
{
strcpy_s(name,20,const_cast <const char*>(emp.name));
emp.salary=salary;
return *this;
}
employee::~employee()
{
delete [] name;
}
Main:
#include <iostream>
#include "class.h"
using namespace std;
int main()
{
employee emp1 ("Bill Jones",5000),emp5("Michael Adams");
employee emp2;
emp2=emp1;
employee emp3;
emp3=emp2;
employee * workers= new employee [3];
workers[0]=emp3;
workers[1]= employee("katy Ashton");
delete [] workers;
}