You are on page 1of 8

Constructors and Destructors

5.1 Introduction:
A constructor may be defined as the special member function that has
the name same as that of the class in which has been defined.
Compiler identifies a given member function as a constructor by its name
and the return type.
Constructor has the same name as that of the class and it does not have
any return type. Also, the constructor is always public.
When a class contains a constructor, it is guaranteed that an object created
with that class will be initialized automatically.
This is very helpful when we want generate an array of object and want it
to be initialized to some default value.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:
1. Constructor has same name as the class itself
2. Constructors don’t have return type
3. A constructor is automatically called when an object is created.
4. If we do not specify a constructor, C++ compiler generates a default
constructor.
Example:
#include<iostream.h>
#include<conio.h>
class MyClass // The class
{
public: // Access specifier
MyClass() // Constructor
{
cout << "BAMU University!!”;
}
};
int main()
{
Clrscr();
MyClass myObj; // Object created , this will call the constructor
getch();
return 0;
} Output:

MyClass myObj1, myObj2, myObj3;

MyClass xyz,abc;
// MyClass commented

45
Constructors and Destructors
Characteristics of Constructors in C++
I. They should be declared in the public section.
II. They are called automatically when the objects are created.
III. All objects of the class having a constructor are initialized before use.
IV. They do not have return (data type) type not even void and there for they
cannot return any values.
V. They cannot be inherited; a derived class can call the base class
constructor.
VI. They cannot be static.
VII. They can have default arguments as other C++ functions.
VIII. They can call member functions of its class.
IX. Constructors cannot be virtual
X. Default and copy constructors are generated by the compiler wherever
required.
XI. Generated constructors are also public.
XII. An object of a class with a constructor cannot be used as a member of
a union.
XIII. We cannot refer to their address.
XIV. They make implicit calls to the operator new and delete when memory
allocation is required.
5.2 Default constructors:
Default constructor is the constructor which doesn’t take any argument. It
has no parameters.
Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.
Example:
/* 13 Program to demonstrate use of Default constructors */
#include <iostream.h>
#include <conio.h>
class xyz
{
public:
int a, b;
xyz() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
clrscr();
xyz c; Output:
cout << "a: " << c.a << endl
<< "b: " << c.b;
getch();
return 1;
}
46
Constructors and Destructors
5.3 Parameterized constructors
Constructors can also take parameters just like regular function,
the constructor take arguments are called as Parameterized constructors.
This type of constructor allows us to pass arguments while object is
created, helping us to assign initial value to an object at the time of its creation.
To create a parameterized constructor, simply add parameters to it the way
you would to any other function. When you define the constructor’s body, use the
parameters to initialize the object.
When a constructor is parameterized the object, declaration statements
such as “ClassName Obj1;” may not work.
We must pass the initial values as arguments to the constructor function
when an object is declared this is done in two ways
1. Calling the constructor explicitly
2. Calling the constructor implicitly
The following demonstration illustrate the first method
Classname obj1 = constructorName(0:10)
Statement above creates an object ‘obj1’ and passes the values 0 & 10 to it
Second method sometimes called as the shorthand method is used very
often as it is short looks better and easier to implement.
Classname obj1 (0:10)
When the construct is parameter appropriate augments must always be
provided for the constructor
Example:
/* Program to demonstrate the use of Parameterized constructors */
#include<iostream.h>
#include<conio.h>
class Addition
{
int a, b, sum; // Variable Declaration
public:
Addition(int x, int y) // Parameterized Constructor created
{ a = x;
b = y; Output:
sum = a + b;
cout << "I’m Constructor\n\n";
}
void Display()
{ cout << "Addition of two numbers = " << sum << "\n" ;
}
};
int main()
{ Addition Object(10, 20); // Constructor invoked
Object.Display();
getch();
return 0;
}
47
Constructors and Destructors
5.4 Multiple constructors in a class:
In C++, we can have more than one constructor in a class with same name,
as long as each has a different list of arguments. This concept is known as
Multiple constructors in a class.
The Multiple constructors in a class is also known as Constructor
Overloading and is quite similar to function overloading.
Overloaded constructors essentially have the same name (name of the
class) and different number of arguments.
A constructor is called depending upon the number and type of arguments
passed.
We can have a default and a parameterized constructor in a class at the
same time.
Example:
/*Program to demonstrate the use of Multiple constructors in a class*/
#include<iostream.h>
#include<conio.h>
class area
{
public:
float area;
area() // Constructor with no parameters
{
area = 0;
}
area(int a, int b) // Constructor with two parameters
{
area = a * b;
}
void disp()
{
cout<< area << endl;
}
};
int main()
{
area A1, A2( 30, 40); // Two different type of constructors of a class
A1.disp();
A2.disp();
getch();
return 0;
}
Output:

48
Constructors and Destructors
5.5 Copy Constructor:
The copy constructor is a constructor which creates an object by initializing
it with an object of the same class, which has been created previously.
The copy constructor is used to −
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
Common form of copy constructor is –
classname (const classname &obj)
{
// body of constructor
}
Here,
obj is a reference to an object that is being used to initialize another object.
Also, the copy constructor argument should be const because we don’t
want the values of old objects to be modified inside the body of this constructor.
/*Program to demonstrate the use of Copy Constructor in a class*/
#include <iostream.h>
#include <conio.h>
class A
{
int x, y;
public:
A(int a, int b)
{
cout << "Parametrized Constructor called! \n";
x = a;
y = b;
}
A(const A &old) // old is the old object being passed
{
x = old.x; //This object's x to old object's x
y = old.y;
cout << "Copy Constructor called! \n";
}
void print()
{
cout << x << " " << y << "\n";
}
};
int main()
{
A obj1(10, 20); // making a object of class A -- >Implicit
A obj2(obj1); // Copy Constructor called old object 'obj' is passed
obj2.print();
getch();
return 0;
}

In the above code, two objects, namely obj and obj2, are created. First object
obj is using the parameterized constructor to create it.
It leads to the assignment of value 10 & 20 to the member variables of
object obj. Then object obj2 is created using object obj. Object obj is passed as an
argument. This leads to the assignment ‘x=old.x’ and ‘y=old.y.’
49
Constructors and Destructors
Concept of deep copy and Shallow copy

Copy Constructor is of two types


1. Default Copy constructor: The compiler defines the default copy
constructor. If the user does not define a copy constructor, compiler
supplies its constructor.
2. User Defined Copy constructor: The programmer defines the user-
defined constructor.
The types of copies are produced by the constructor:
1. Shallow Copy of Constructor: In default copy constructor shallow copy
occurs. In shallow copy variables of the new object gets the values of the
old object but they point to the same memory as of the old object.
2. Deep Copy of Constructor: Deep copy is possible only with user
defined copy constructor. We make new memory for each variable and
then assign the same value as the old value of the old object.

/* Program to demonstrate the use of Shallow Copy Constructor */


#include <iostream.h>
#include <conio.h>
class A
{
int x, y;
public:
A(int a, int b)
{
cout << "Parametrized Constructor called! \n";
x = a;
y = b;
}
void print()
{
cout << x << " " << y << "\n";
}
};
int main()
{
A obj1(10, 20); // making a object of class A -- >Implicit
A obj2(obj1); // Copy Constructor called old object 'obj' is passed
obj2.print();
getch();
return 0;
}

Two objects have been created in the above code, First obj1 by a simple
parameterized constructor. The second obj2 uses copy constructor and the first
object obj1 is passed to it. As no copy constructor is defined the compiler defines
a default copy constructor thus a Shallow Copy of Constructor is created.
50
Constructors and Destructors
5.6 Destructors:
Destructor is the special member function that automatically deletes or
destructs an object (instance of a class) to release memory or close a file when it
goes out of its scope.
A destructor is called when:
1. Termination of a program: When the object is declared with a global scope
or with static class, a destructor is executed automatically when the
program ends to clear up the memory taken by that object.
2. The flow of control out of a block: In the case where objects are defined
with local scope in a specific block, the destructor is called when the
execution control gets out of that particular block, then be it a function,
loop or condition.
3. Explicit destructor call: Sometimes it is necessary to explicitly call a
destructor in order to clean up resources at absolute addresses which may
not be possible with delete operator because that memory was never
allocated from free space.
Syntax:
~class_name() { };
Its syntax is same as constructor except the fact that it is preceded by the tilde
sign.
Example:
/*14 Program to demonstrate the use of Destructors */
#include <iostream.h>
#include <conio.h>
class HelloWorld
{
public:
HelloWorld() //Constructor
{
cout<<"Constructor is called"<<endl;
cout<<"Hello World!"<<endl;
}
~HelloWorld()//Destructor
{
cout<<"Destructor is called"<<endl;
}
};
int main()
{
HelloWorld obj; //Object created
return 0;
}
Output:

51
Constructors and Destructors
Destructor rules:
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any
parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a
default destructor and inserts it into your code.
6) There Cannot be more than one destructor in a class.
7) Destructor can’t be overloaded.

52

You might also like