You are on page 1of 9

Constructors and Destructors in C++

What is constructor?
A constructor is a special type of member function of a class which initializes objects of a
class. In C++, Constructor is automatically called when object (instance of class) is created.
It is special member function of the class because it does not have any return type.

How constructors are different from a normal member function?


A constructor is different from normal functions in following ways:
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• It must be placed in public section of class.
• If we do not specify a constructor, C++ compiler generates a default constructor for
object (expects no parameters and has an empty body).

Types of Constructors
1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters. Below is an example of a default constructor:
#include <iostream>
using namespace std;

class construct
{
public:
int a, b;
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 0;
}

Output:
a: 10
b: 20

Note: Even if we do not define any constructor explicitly, the compiler will automatically
provide a default constructor implicitly.
2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically,
these arguments help initialize an object when it is created. 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.
#include <iostream>
using namespace std;

class Point
{
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

return 0;
}

Output:
p1.x = 10, p1.y = 15

When an object is declared in a parameterized constructor, the initial values have to be


passed as arguments to the constructor function. The normal way of object declaration may
not work. The constructors can be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call


Example of implicit and explicit call

#include <iostream>
using namespace std;

class student
{

public: int roll;


float percent ;
student (int a, float b)
{
roll=a;
percent=b;

}
};

int main()
{
student z= student(1000,78.89); /*explicit call to constructor*/
student x(2000, 56.78); /* implicit call to constructor */
cout << "Roll number = " << z.roll << " obtained percentage= " << z.percent<<endl;
cout << "Roll number = " << x.roll << " obtained percentage= " << x.percent;
return 0;
}

Output:
Roll number =1000 obtained percentage=78.99
Roll number =2000 obtained percentage=56.78

• Uses of Parameterized constructor:


o It is used to initialize the various data elements of different objects with different
values when they are created.
o It is used to overload constructors.
• Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.

3. Copy Constructor:
A copy constructor is used to declare and initialize an object from another object. The
process of initializing through a copy constructor is known as copy initialization. A reference
variable has been used as an argument to the copy constructor. We cannot pass argument
by value to the copy constructor. When no copy constructor is defined the complier supplies
its own copy constructor.
A copy constructor is a member function that initializes an object using another object of the
same class. A copy constructor has the following general function prototype:
ClassName (ClassName &old_obj);

Following is a simple example of copy constructor.


#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(Point &p1) {x = p1.x; y = p1.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

return 0;
}

Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

Below is another example involving default constructors, parametrized constructors and


copy constructors:
class sample
{
int a,b;
public: sample() {a=10; b=20;} /* default constructor */
sample( int x, int y=99) {a=x; b=y;} /* parameterized constructor */
sample( sample &p) { a=p.a; b=p.b;} /* copy constructor*/
void display()
{ cout<<a<< " "<<b<<endl;}
};

int main()
{
sample z; /* default constructor called */
sample y(88); /* parameterized constructor called);*/
sample w(77,66); /* parameterized constructor called);*/
sample m(w); /*copy constructor called;*/
z.display();
y.display();
w.display();
m.display();
return 0;
}

Output:
10 20
88 99
77 66
77 66

Copy constructor vs Assignment Operator


Which of the following two statements call copy constructor and which one calls assignment
operator?
MyClass t1, t2;
MyClass t3 = t1; // ----> (1)
t2 = t1; // -----> (2)

Copy constructor is called when a new object is created from an existing object, as a copy
of the existing object. Assignment operator is called when an already initialized object is
assigned a new value from another existing object. In the above example (1) calls copy
constructor and (2) calls assignment operator.

Dynamic initialization of object in C++


• Dynamic initialization of object refers to initializing the objects at a run time i.e., the
initial value of an object is provided during run time.
• It can be achieved by using constructors, by passing parameters to
the constructors.
• This comes in really handy when there are multiple constructors of the same class
with different inputs.

DYNAMIC CONSTRUCTORS
The constructor can be used to allocate memory while creating objects which enables the
system to allocate the right amount of memory for each object when the objects are not of
same size.
Allocation of memory to objects at the time of construction is known as dynamic construction
of objects.

#include <iostream>
#include <string.h>

using namespace std;

class sample
{
char *name;
int length;
public:
sample()
{ length=0; name= (char*) malloc(length+1);}

sample(char *s)
{ length=strlen(s); name= (char*) malloc(length+1); strcpy(name,s);}

void display()
{cout<<name<<endl;}
};

int main()
{
sample s1;
sample s2("Computer Science");
s1.display(); //no memory created for s1
s2.display(); //memory as per requirement created for s2
return 0;
}

Output:
Computer Science

Constructor Overloading in C++


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 Constructor.
• Overloaded constructors essentially have the same name (exact name of the
class) and differ by number and type of arguments.
• A constructor is called depending upon the number and type of arguments passed.
• While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
Below is an example:
#include <iostream>
using namespace std;

class construct
{

public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}

// Constructor with two parameters


construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};

int main()
{
construct o;
construct o2(10,20);

o.disp();
o2.disp();
return 1;
}
Output:
0
200

Destructors in C++
Destructor is an instance member function which is invoked automatically whenever an
object is going to be destroyed. Meaning, a destructor is the last function that is going to be
called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the constructor uses
new to allocate memory which resides in the heap memory or the free store, the destructor
should use delete to free the memory.
Syntax:
~constructor-name();

Properties 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.
When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
How are destructors different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

Let's see an example of constructor and destructor in C++ which is called automatically.
#include <iostream>
using namespace std;

class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
cout << "Function main is terminating...." << endl;
return 0;
}

Output:
Constructor Invoked
Constructor Invoked
Function main is terminating....
Destructor Invoked
Destructor Invoked

Another example of a destructor to understand the order in which destructors are called:
#include <iostream>
using namespace std;

class test1{
public:
~test1 () {cout << "Test1 Destructor called" << endl;}
};
class test2{
public:
~test2 () {cout << "Test2 Destructor called" << endl;}
};

int main()
{
test1 A;
test2 B;
return 0;

OUTPUT
Test2 Destructor called
Test1 Destructor called

Another example of constructor and destructor:


#include <iostream>
using namespace std;

class Rectangle
{
int length;
int breadth;
public:
void setDimension(int l, int b)
{
length = l;
breadth = b;
}
int getArea()
{
return length * breadth;
}
Rectangle() // Constructor
{
cout << "Constructor called" << endl;
}
~Rectangle() // Destructor
{
cout << "Destructor called" << endl;
}
};

int main()
{
Rectangle rt;
rt.setDimension(7, 4);
cout << rt.getArea() << endl;
return 0;
}

Output:
Constructor called
28
Destructor called

Can there be more than one destructor in a class?


No, there can only one destructor in a class with classname preceded by ~, no parameters
and no return type.
When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us.
The default destructor works fine unless we have dynamically allocated memory or pointer
in class. When a class contains a pointer to memory allocated in class, we should write a
destructor to release memory before the class instance is destroyed. This must be done to
avoid memory leak.

You might also like