C++ Constructors And Destructors

C++ provides us with a mechanism to initialize an object during creation through a constructor, same way C++ also provides us with a mechanism to destroy an object through a destructors.

Constructors In C++

A member function whose name is the same as the class name is called a constructor, and that member function is used to initialize the object of that class type with an initial value.

Syntax :

class LFC
{
public:
int a;
// constructor
LFC()
{
// object initialization
}
};

Constructors can be defined outside the class definition or inside the class definition by using the class name or workspace resolution :: operator.



Syntax:

class A
{
public:
int i;
A(); // constructor declared
};
// constructor definition
A::A()   
{
i = 1;
} 

Types of Constructors in C++

Default Constructors

A constructor that does not accept any parameter that is known as default constructors or we can say that constructor without any arguments is known as default constructor. It has no parameter. If there is no constructor in the class, the compiler automatically creates the default constructor.

Syntax :

class-name()
{ 
// constructor Definition 
}


Example:
class Square
{
public:
int edge;
Square()
{
edge = 30;
}
};
int main()
{
Square s;
cout << s.edge;
} 


Output:
30


In the example, when the object of the class square is created, the default constructor is called which initializes its data member (edge) with the value 30, and then cout will print the output to the screen.

Parameterized Constructors

A constructor that accept any number of parameter is known as Parameterized constructors or we can say that constructor with an arguments is known as Parameterized constructor. When we create a parameterized constructor, we have to pass a argument value at the time of object creation for that class.

Example:

class Square
{
public:
int edge;
Square(int x)
{
edge=x;
}
};
int main()
{
Square s1(100);
Square s2(200);
Square s3(300);
cout << s1.edge;
cout << s2.edge;
cout << s3.edge;
} 


Output:
100
200
300

In the example, when the object of the class square is created, we have initialized 3 objects(s1, s2, s3) with user defined values(100, 200, 300) and then we print the output to the screen.

Copy Constructors

C++ has a special type of constructor that takes an object as an argument and then copies the value of one object's data member to another object. A copy constructors is called whenever a new variable is created from an object.

Syntax:

Classname(const classname & objectname)
{
. . . . . .
}


Example:
#include<iostream>
using namespace std;
class Sample
{
private:
int a, b;   //data members
public:
Sample(int x1, int y1)
{
a = x1;
b = y1;
}
/* Copy constructor */
Sample(const Sample &sam)
{
a = sam.a;
b = sam.b;
}
void print()
{
cout<< a<<" "<< b<< endl;
}
};
/* main function */
int main()
{
Sample s1(5, 75);     // Normal constructor
Sample s2 = s1;      // Copy constructor
cout<<"Normal constructor : ";
s1.print();
cout<<"Copy constructor : ";
s1.print();
return 0;
}


Output:
Normal constructor : 5 75
Copy constructor : 5 75

C++ Destructors

A destructor is a class function that destroys the object as soon as the object's scope is over, and the destructor name is the same as the class name but precedes by the tilde (~). The destroyer destroys the value of the object as it goes out of scope.

Syntax:

class X
{
public:
// defining destructor for class
~X() 
{
// statement
}   
};


Example:
#include<iostream>
using namespace std;
class X
{
public:
// constructor
X()
{
cout << "Constructor called\n";
}
// destructor
~X()
{
cout << "Destructor called\n";
}
};
int main()
{
X sam;   // Constructor Called
int y = 1;
if(y)
{
X sam1;  // Constructor Called
}   // Destructor Called for sam1
} //  Destructor called for sam


Output:
Constructor called
Constructor called
Destructor called
Destructor called

Difference between Constructor and Destructor

Constructor Destructor
Constructor has the same name as class name. Destructor also has the same name as class name but with (~) tiled operator.
Constructors can have arguments. Destructor does not have any argument.
Constructor allocates the memory. Destructor releases the memory.
Constructor is used to initialize the instance of a class. Destructor destroys the objects when they are no longer needed.
Overloading of constructor is possible. Overloading of Destructor is not possible.

Difference between Default and Parameterized constructor

Default Constructor Parameterized Constructor
A constructor which takes no arguments A constructor which takes one or more arguments
No need to pass any parameters while constructing new objects At least one or more parameters need to be passed while constructing new objects
Initializing objects with the same data Create distinct objects with different data

Exercise:-

1. Which of the followings is/are automatically added to every class, if we do not write our own.

A. Copy Constructor
B. Assignment Operator
C. A constructor without any parameter
D. All of the above

View Answer


2. When a copy constructor may be called?

A. When an object of the class is returned by value.
B. When an object of the class is passed (to a function) by value as an argument.
C. When an object is constructed based on another object of the same class
D. When compiler generates a temporary object.
E. All of the above

View Answer



Program

C++ program to demonstrate example of destructors

#include 
using namespace std;
//Class Declaration
class Demo
{
private: //Private Data member section
int X,Y;
public://Public Member function section
//Default or no argument constructor.
Demo()
{
X = 0;
Y = 0;
cout << endl << "Constructor Called";
}
//Destructor called when object is destroyed
~Demo()
{
cout << endl << "Destructor Called" << endl;
}
//To take user input from console
void getValues()
{
cout << endl <<"Enter Value of X : "; cin >> X;
cout << "Enter Value of Y : "; cin >> Y;
}
//To print output on console
void putValues()
{
cout << endl << "Value of X : " << X;
cout << endl << "Value of Y : " << Y << endl;
}
};
//main function : entry point of program
int main()
{
Demo d1;
d1.getValues();
cout << endl <<"D1 Value Are : ";
d1.putValues();
Demo d2;
d2.getValues();
cout << endl <<"D2 Value Are : ";
d2.putValues();
//cout << endl ;
return 0;
}


Output:
Number: 12
Enter data: 23.3
You entered 23.3  



Visit :


Discussion



* You must be logged in to add comment.