Default Constructors

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?

Thanks!!

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  #include <iostream>
using namespace 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;
}
Last edited on
Constructors are called when an object is created
1
2
3
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; 
    }
};
Topic archived. No new replies allowed.