CONSTUCTOR
CONSTUCTOR
o Default constructor
o Parameterized constructor
Constructors do not return values; hence they do not have a return type. Constructors can be
overloaded. Constructor cannot be declared virtual.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0; }
DefaulDefault Constructor Invoked
Default Constructor Invoked
t Constructor Invoked
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance
variable)
string name;//data member(also instance
variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<"
"<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000);
//creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
101 Sonoo 890000
102 Nakul 59000
Default Constructor Invoked
Default Constructor Invoked
1. Constructor Invoked
C++ DESTRUCTOR
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed
with a tilde sign (~).
C++ DESTRUCTOR
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on
destructors.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
another object.
o When we initialize the object with another existing object of the same class type. For example,
Student s1 = s2, where Student is the class.
o When the object of the same class type is passed by value as an argument.