I was trying out a simple code below
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class employee
{
private:
int emp_id;
public:
void getEmpid(){cout<<emp_id<<endl;}
void setEmpid(){ cin>>emp_id;}
employee():emp_id(10){cout<<"construct 1 "<<"employee id "<<emp_id<< endl;}
employee(int empid):emp_id(empid){cout<<"construct 2 "<<"employee id "<<emp_id<<endl;}
employee(const employee &emp):emp_id(emp.emp_id){cout<<"copy construct 3 "<<"employee id "<<emp_id<<endl;}
employee(employee&& other) : emp_id(other.emp_id) {cout<<"move construct 4 "<<"employee id "<<emp_id<<endl;}
~employee(){cout<<"destructor"<<endl;}
};
int main()
{
vector<employee>a;
employee s[8]={1,2,3,4,5};
for(int i=0;i<sizeof(s)/sizeof(s[0]);i++)
a.push_back(s[i]);
a.push_back(20);
a.push_back(30);
a.push_back(40);
a.push_back(50);
a.push_back(60);
for(int i=0;i<a.size();i++)
a[i].getEmpid();
return 0;
}
*I get the below output. Not very clear how the constructors and destructors are called and in which order. could some one please throw some light? *
Output:
construct 2 employee id 1
construct 2 employee id 2
construct 2 employee id 3
construct 2 employee id 4
construct 2 employee id 5
construct 1 employee id 10
construct 1 employee id 10
construct 1 employee id 10
copy construct 3 employee id 1
copy construct 3 employee id 2
copy construct 3 employee id 1
destructor
copy construct 3 employee id 3
copy construct 3 employee id 1
copy construct 3 employee id 2
destructor
destructor
copy construct 3 employee id 4
copy construct 3 employee id 5
copy construct 3 employee id 1
copy construct 3 employee id 2
copy construct 3 employee id 3
copy construct 3 employee id 4
destructor
destructor
destructor
destructor
copy construct 3 employee id 10
copy construct 3 employee id 10
copy construct 3 employee id 10
construct 2 employee id 20
move construct 4 employee id 20
copy construct 3 employee id 1
copy construct 3 employee id 2
copy construct 3 employee id 3
copy construct 3 employee id 4
copy construct 3 employee id 5
copy construct 3 employee id 10
copy construct 3 employee id 10
copy construct 3 employee id 10
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
construct 2 employee id 30
move construct 4 employee id 30
destructor
construct 2 employee id 40
move construct 4 employee id 40
destructor
construct 2 employee id 50
move construct 4 employee id 50
destructor
construct 2 employee id 60
move construct 4 employee id 60
destructor
1
2
3
4
5
10
10
10
20
30
40
50
60
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor
destructor