User Menu

Login



Share with

Constructor and Destructor in C++ PDF Print E-mail

Constructor and Destructor Member Functions

Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared).

Destructor:- A destructor is a automatically called member function of a class, when an object is destroyed of that class.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Use of Constructor and Destructor function of a class: -

  1. 1.Constructor function is used to initialize member variables to pre-defined values as soon as an object of a class is declared.
  2. 2.Constructor function having parameters is used to initialize the data members to the values passed values, upon declaration.


Generally, the destructor function is needed only when constructor has allocated dynamic memory.

Defining Constructor and Destructor functions

The example below illustrates how constructor and destructor functions are defined:

class Kangra
{
private:
int n;

public:
Kangra() //constructor
{
n=1;
}
~Kangra() //destructor
{ }
};

A few points to note:

  • Both of the functions have the same name as that of the class, destructor function having (~) before its name.
  • Both constructor and destructor functions should not be preceded by any data type (not even void).
  • These functions do not (and cannot) return any values.
  • We can have only the constructor function in a class without destructor function or vice-versa.
  • Constructor function can take arguments but destructors cannot.
  • Constructor function can be overloaded as usual functions.

Explicit call to the constructor: - By explicit call to the constructor,means that the constructor is explicitly declared by the programmer inside the class.

Implicit call to the constructor: - By implicit call to the constructor,means that the constructor is implicitly provided by the Compiler when an Object of the Class is created and there is no Explicit Constructor defined inside the Class.

Example 1: Explicit constructor function to initialize data members to pre-defined values

#include<iostream.h>
class Kangra
{
private:
int a;
int b;

public:
Kangra()
{
//here constructor function is used to initialize data members to pre-defined values 
a=10;
b=10;
}

int add()
{
return a+b;
}
};
int main(void)
{
Kangra obj;
cout<<obj.add();
return 0;
}

Example 2: Explicit constructor function to initialize data members to values passed as arguments

#include<iostream.h>
class Kangra
{
private:
int a;
int b;

public:
Kangra(int i, int j)//Explicit Constructor with arguments
{
a=i;
b=j;
}

int add(void)
{
return a+b;
}
};
int main()
{

myclass obj(10,20); //This Can be written as Kangra obj obj=Kangra(10,20);
cout<<obj.add();
}
Default/Implicit constructor: - These constructors are inserted automatically by the Compiler into class declarations that do not have any implicit constructor.

Example:

class Ayan

{

Ayan() { } //Default/Implicit Constructor

};

Copy Constructor

A copy constructor is a special constructor that creates a new object from an existing object. If we do not define a copy constructor, the compiler will generate one for us that performs a shallow copy (copies only a pointer so that the two pointers refer to the same object) of the existing object's member variables. So, if our object allocates any resources, we most likely need a copy constructor so that we can perform a deep copy (copies what a pointer points to so that the two pointers now refer to distinct objects).

// Shallow Copy Example

char *ch = new char('Z');

char *cp = ch; // copy the pointer ch

*ch = 'X'; // change the value of the char pointed to by *ch

// Deep Copy Example

int *p = new int(99);

int *q = new int(*p);

// Allocate a new int before copying the value pointed to by p

*p = 100; // change the value of the int pointed to by p

Example of Default Copy Constructor that compiler provides and its problem:

#include <iostream.h>

#include<string.h>
class Kangra
{
int *temp;
public:

Kangra(int i)

{
cout << " Constructor";
temp=new int();
*temp = i;
}

~Kangra()
{
cout << "Destructor";
delete temp;
}
};

int main()
{
Kangra kg(150); // First Object Created Invoke our Constructor
Kangra kg1(kg); // Here is the Problem;

/* When Second Object will be  Created It will not Invoke our Constructor. It will invoke Default Copy Constructor */

cout << "Main";
return 0;
}

Let's look at the output:

Constructor

Main

Destructor

Destructor

Null Pointer Assignment 

Destructor does delete. The problem is it is trying to delete a pointer we haven't allocated. When default copy constructor is called (Kangra kg1(kg)), it does not allocate anything.

How to fix it?

Use explicit Copy Constructor Instead of Default Copy Constructor

#include<iostream.h>

#include<string.h>
class Kangra
{
int *temp;
public:

Kangra(int i)
{
cout<<"Constructor\n";
temp=new int();
*temp=i;
}
Kangra(const Kangra &obj) // Explicit Copy Constructor

{
cout << "Copy Constructor\n";
temp = new int();
*temp=*obj.temp ;
}
~Kangra()
{
cout << "Destructor\n";
delete temp;
}
};

int main()
{
Kangra kg(150); // Call to Simple Constructor when Object 1 will be created
Kangra kg1(kg); // Call to Explicit Copy Constructor when Object 2 will be created

cout << "Main\n";

return 0;
}

Now we will get the desired output: Two Objects Created and Two Deleted

Constructor

Copy Constructor

Main

Destructor

Destructor

This should be our choice.

Summary

The copy constructor gets called in the following cases:

An object is passed to a method by value or returned by value.

An object is initialized using the syntax, MyClass a = b.
An object is thrown or caught in an exception.

Constructor with Default Argument:

#include <iostream.h>

#include<string.h>

class Kangra
{
int temp;
public:

Kangra(int i=10) //Constructor with Default Argument 10

{

cout << " Inside Constructor with Default Argument";
temp=i;
cout<<"Temp = "<<temp;
}

};

int main()

{
Kangra kg; // Object Created without argument. This will take default argument of the Constructor

cout << "Main";
return 0;
}

Output:

Inside Constructor with Default Argument

temp=10;

Main

scroll back to top