Pages

Friday, September 9, 2016

C++ Program to show various types of Constructors and Destructors

Program-

#include<string.h>
#include<iostream>
using namespace std;

class Emp
{
char name[10];
float sal;
public:
Emp()
{
strcpy(name," ");
sal=0.0;
cout<<"\nDefault Constructor is called\n";
}
Emp(char * str,float s)
{
strcpy(name,str);
sal=s;
}

Emp(Emp &e)
{
strcpy(name,e.name);
sal=e.sal;
}
void input()
{
cout<<"Enter Name and salary\n";
cin>>name>>sal;
}
void put()
{
cout<<"\nName= "<<name;
cout<<"\nSalary= "<<sal;
}

~Emp()
{
cout<<"\n\n-----------Destructor Called-------------";
}
};
int main()
{
cout<<"------Default Constructor ----------\n ";
Emp e1;
e1.input();
e1.put();
cout<<"\n\n------Parameterized  Constructor where Rajesh and 50000 are passed -------\n ";
Emp e2("Rajesh",50000);
e2.put();
cout<<"\n\n------Copy Constructor where e1 is copied-------------\n ";
Emp e3(e1); //implicit call or e3=e1; //explicit call
e3.put();


return 0;
}


Output-

------Default Constructor ----------

Default Constructor is called
Enter Name and salary
Bablu
40000

Name= Bablu
Salary= 40000

------Parameterized  Constructor where Rajesh and 50000 are passed -------

Name= Rajesh
Salary= 50000

------Copy Constructor where e1 is copied-------------

Name= Bablu
Salary= 40000

-----------Destructor Called-------------

-----------Destructor Called-------------

-----------Destructor Called-------------

No comments:

Post a Comment