Constructors and Destructors
Constructors and Destructors
Lecture 04
Constructors
Types of Constructors
Constructor Overloading
Destructors
– Parameterized Constructor
• Have parameters
Types of constructors
• Default Constructor
• Takes no parameters
• Example:
class Point{
private:
int x,y;
public:
Point(){ //Default ctor
x = 0;
y = 0;
cout<<“I am default ctor of Point class”<<endl;
}
};
int main()
{
Counter c1, c2; //define and initialize
cout << “\nc1=” << c1.get_count(); Output
cout << “\nc2=” << c2.get_count(); c1=0
c1.inc_count(); //increment c1
c2=0
c2.inc_count(); //increment c2
c2.inc_count(); //increment c2 c1=1
cout << “\nc1=” << c1.get_count(); c2=2
cout << “\nc2=” << c2.get_count();
}
Destructors
• A special member function
• Called automatically when object of that class is
destroyed.
• Has the same name as the class it belongs to
followed by a ~ sign
• No return type is used for destructors
• Destructors can not be parameterized
• Destructors can not be overloaded
• Purpose of Destructor
– Perform task needed at the time of object killing like
• Release resources acquired by an object
• De-allocation of run time memory
Destructors
• An example
class Counter{
private:
int count;
public:
Counter() : count(0){
cout<<“I am ctor of Counter class”<<endl;
}
~Counter(){ //Destructor of Counter class
cout<<“I am dtor of Counter class”<<endl;
}
};
void main(){
cout<<“Start of main”<<endl; Output
Counter a; Start of main
{ cout<<“Inside the block”<<endl; I am ctor of Counter class
Counter b; Inside the block
cout<<“Exiting block”<<endl; I am ctor of Counter class
} Exiting block
cout<<“Exiting main”<<endl; I am dtor of Counter class
} Exiting main
I am dtor of Counter class