Unit 3 Constructor and Destructor
Unit 3 Constructor and Destructor
Unit 3 Constructor and Destructor
Unit – 3
Computer Dept P a g e |1
BOOP -4320702 Term-212 Sem-2
Characteristics of Destructor:
➢ 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.
Syntax:
class Employee {
public:
int age;
//default constructor
Employee() {
//data member is defined with the help of default constructor
age = 50;
}};
int main() {
//object of class Employee declared
Employee e1;
//prints value assigned by default constructor
cout << e1.age;
return 0;
}
Types of Constructor
1. Default constructor
2. Parameterized constructor
3. Copy constructor
1. Default Constructor:
➢ The default constructor is the constructor which doesn't take any argument. It has
no parameter but a programmer can write some initialization statement there
➢ A default constructor is very important for initializing object members, that even if
we do not define a constructor explicitly, the compiler automatically provides a
default constructor implicitly.
#include<iostream>
using namespace std;
class item{
private:
int code;
int price;
public:
item ();
};
#include<iostream>
using namespace std;
class item{
private:
int code;
int price;
public:
item (int, int);
};
item :: item (int p, int q){
code=p;
price=q;
cout<<code<<endl;
cout<<price<<endl;
}
int main(){
item i1=item(10,20); //explicit call
item i2 (1,2); //implicit call
return 0;
}
Output :
10
20
1
2
#include<iostream>
using namespace std;
class item{
private:
int code;
int price;
public:
item ();
};
int main(){
item i1[2];
return 0;
}
Output:
1 100
1 100
#include<iostream>
using namespace std;
class item{
private:
int code;
int price;
public:
item (int, int=22);
};
item :: item (int p, int q){
code=p;
price=q;
cout<<code<<endl;
cout<<price<<endl;
}
int main(){
item i1=item(10); //explicit call
item i2 (1,2); //implicit call
item i3 (11);
return 0;
}
Output:
10 22 1 2 11 22
3.9 Destructor:
➢ As the name implies, destructors are used to destroy the objects that have been created
by the constructor within the C++ program.
➢ Destructor names are same as the class name but they are preceded by a tilde (~).
➢ It is a good practice to declare the destructor after the end of using constructor.
#include<iostream>
using namespace std;
int c=0;
class test
{ public:
test(){
c++;
cout<<"\n Object Created"<<c<<endl;
}
Be ready to do it in time!
Assignment-3