Hey guys! I was studying constructors in class but my teacher failed to put a concept in my mind. My first question is, what do constructors do? Which kind of constructor is the most frequently used? How to work with the "default constructor"?
I want to put a constructor in this code... Default constructor that initializes name and ID as NIL and salary and years of service as 0. Where should the constructor be placed?
#include <iostream>
usingnamespace std;
class employee
{
private:
string name;
string id;
int salary;
int years_of_service;
public:
void setname(string nm)
{
name = nm;
}
void setid(string id1)
{
id = id1;
}
void setsalary(int sal)
{
salary = sal;
}
void set_yos(int yos)
{
years_of_service = yos;
}
void output()
{
cout<<name<<", Employee ID # "<<id<<" has served the company for "<<years_of_service<<" years and his/her salary is "<<salary<<" rupees.\n\n";
}
};
int main()
{
employee e1;
string nm1;
string id2;
int sal1;
int yos1;
char ans;
cout<<"Enter employee details below.\n\n";
cout<<"Enter name: ";
getline(cin, nm1);
e1.setname(nm1);
cout<<"Enter employee ID: ";
getline(cin, id2);
e1.setid(id2);
cout<<"Enter salary: ";
cin>>sal1;
e1.setsalary(sal1);
cout<<"Enter employee's years of service: ";
cin>>yos1;
e1.set_yos(yos1);
cout<<"\n\nDo you want to view the details added just now (Y/N)? ";
cin>>ans;
if((ans=='Y' && ans=='Y') || (ans=='y' && ans=='y'))
{
e1.output();
}
else
{
cout<<"\n\nHey! Don't shit with me! Now do the whole thing again 'cause I haven't put it on a loop!\n\n";
}
return 0;
}
class myClass {};
myClass A; // Creates A and calls default constructor
If you want a constructor for your code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class employee
{
private:
string name;
string id;
int salary;
int years_of_service;
public:
employee() // Default constructor
{
name = "NIL"; // initialize labels
id = "NIL"; // Could use an intializer list, but this is simpler to understand.
salary = 0;
years_of_service = 0;
}
};