Oops
Oops
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Output:
Employee e2;
Default Constructor Invoked
return 0;
Default Constructor Invoked
}
Parameterized Constructor
• It is possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created.
• It is used to provide different values to distinct objects.
• It is used to overload constructors.
#include <iostream>
using namespace std;
Example
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
Employee(int i, string n) //parameterized constructor
{
id = i;
name = n;
}
void display()
{ cout<<id<<" "<<name<<endl; }
};
int main(void) {
Employee e1 =Employee(101, "Sonoo"); //creating an object of Employee
Employee e2=Employee(102, "Nakul");
e1.display();
e2.display();
return 0;
}
Destructors
• 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 (~).
• Syntax:
~constructor-name();
Properties of Destructors
• Destructor function is automatically invoked when the objects are
destroyed.
• It cannot be declared static or const.
• The destructor does not have arguments.
• It has no return type not even void.
• An object of a class with a Destructor cannot become a member of
the union.
• A destructor should be declared in the public section of the class.
• The programmer cannot access the address of destructor.
When is destructor called?