Constructors and Destructors in C++

Constructors in c++.

Constructor is a special member function which is having same name as classname which is used to automatically initialze data members to some values when an object of the class is created.A constructor could be invoked directly when  an object of the class is created. There is no need to call constructor explicitly.

Before starting constructors in detail, lets   discuss a short example.

These 3 methods are used to initialize data members to certain values.

METHOD 1: Method 1 ,which is a wrong method of initializing data members which are kept private.where we cannot initialize data members through object of class  which are kept private.

Method 2 and method 3

 To initialize data members through objects either get() and set()  member functions are used  or we can make them public through which the data hiding property of class is not used.

Inorder to initialize data members directly without using get() ,set() member function or without making data members public CONSTRUCTORS are used.

Constructor is a  special member function having same name as that of its class which is used to initialize some valid values to the member variables when the object of the class is created.

 Constructor declaration and definition

As discussed above constructor is a special member function which is having same name as classname which is used to automatically initialze data members to some values when an object of the class is created.A constructor could be invoked directly when  an object of the class is created. There is no need to call constructor explicitly.

DECLARATION:

CHARACTERISTICS OF CONSTRUCTORS

  • A constructor has same name as that of the class to which it belongs.
  • A constructor is executed automatically whenever the object is created.
  • A constructor doesn’t have a return type, not even void.
  • A constructor can be declared only in public section of a class.
  • We can declare more than one constructor in a class. These constructor differ in there parameter list.
  • If you don’t provide a constructor of your own then the compiler generates a default constructor (expects no parameters and has an empty body).
  • A constructor can preferably be used for initialization and not for input\output operations.
  • A constructor can be Overloaded but cannot be inherited.
  • Constructor cannot be virtual.
  • It may not be static.

TYPES OF CONSTRUCTOR

Discussing all the 4 types of constructor one by one.

1.DEFAULT CONSTRUCTOR

A default constructor is a constructor which has no parameters.A default constructor can be called directly  when an object of the class is created.If no constructor are created,compiler will create a default constructor by itself.

Program:A programming example of c++ to display value of data members using constructors.:

#include<iostream>
using namespace std;
class Abc
{private:
int a,b;
public:
Abc()  // default constructor
{cout<<"constructor called"<<endl;
a=10;
b=20;
}
void displaydata()
{cout <<"the value of a and b is " <<a<<endl<<b;
}
};
int main()
{Abc obj;   //constructor called directly when object of class is created
obj.displaydata();
return 0;
}

 

2. PARAMETERIZED CONSTRUCTORS

Parameterized constructors are alike parameterized member function i.e here also actual arguments are passed to formal arguments but here the arguments are passed when an object of the class is created(as constructors are invoked immediately when an object of the class is created or declared. 

“Parameterized constructors are those which initialize data members by passing arguments “

 

PARAMETRIZED CONSTRUCTOR CAN BE CALLED BY 3  WAYS

1.By calling the constructor IMPLICITLY

Here we used parameterized constructor with 2 arguments,where the arguments are passed at the time of object creation this is called implicitly calling of an  constructor. Abc is class name  where object is created of name object.

This is also called as shorthand method of calling an constructor.

 2.By calling the constructor EXPLICITLY

Invoking  an constructor explicitly means not passing an arguments when an object is declared rather than calling the constructor  explicitly after object of class  is created.

 

3.Case 3 :Parameterized constructor with one argument.

When we needs to pass only one argument we can pass it directly by assigning value to an object when an object of the class is created or declared. This method is only used in the case of parameter with one argument.

 

Program:A programming example of c++ to display value of data members using  Parameterized constructors.

#include<iostream>
using namespace std;
class Abc
{private:
int a,b;
public:
Abc(int x,int y)//parameterized constructor
{cout<<" Paraterized constructor called "<<endl;
a=x;
b=y;
}
void displaydata()
{cout <<"the value of a and b is" <<a<<endl<<b<<endl;
}
};
int main()
{Abc obj(4,6);//1st call implicit call
obj.displaydata();
return 0;
}

All three types of  parameterized constructors are used  in a single program where object one is created to call constructor implicitly,object 2 is created to call constructor explicitly and 3rd object is made to  invoke constructor explicitly by passing one argument.

#include<iostream>
using namespace std;
class Abc
{private:
int a,b;
public:
Abc(int x,int y)
{cout<<"constructor called "<<endl;
a=x;
b=y;
}
Abc(int x)
{cout<<"constructor called "<<endl;
a=x;
cout<<"value of x is "<<a<<endl;
}
void displaydata()
{cout <<"the value of a and b is" <<a<<endl<<b<<endl;
}
};
int main()
{Abc obj(4,6);//1st call implicit call
Abc obj1=Abc(2,3);//2nd call Explicit
Abc obj2=8;//if one argument can pass  argument directly
obj.displaydata();
obj1.displaydata();
return 0;
}

 PROGRAM 3:A programming example to find area using different constructors.

#include<iostream>
using namespace std;
class Area
{private:
int a,b;
float c;
public:
void triangle()
{cout <<"area of triangle is" ;
c=0.5*a*b;
cout<<c <<endl;
}
void rectangle()
{cout<<"area of rectangle is  "<<a*b<<endl;
}
void circle()
{cout<<"area of circle is  ";
c=3.14*a*a;
cout<<c <<endl;
}
Area(int x,int y)
{cout<<"constructor called "<<endl;
a=x;
b=y;
}
Area(int x)
{cout<<"constructor called "<<endl;
a=x;
}
};
int main()
{Area obj(4,6);//1st call implicit call
Area obj1=Area(2,3);//2nd call Explicit
Area obj2=8;//if one argument can pass  argument directly
obj.triangle();
obj1.rectangle();
obj2.circle();
return 0;
}

 

3.COPY CONSTRUCTOR

A copy constructor as the name tells is used to create a copy of an object that is already created. i.e Copy constructor is a constructor that creates a new object using an existing object of the same class.

As copy constructor is used to declare and initialize an object from an existing object its syntax will be:

THIS DIAGRAM SHOWS DECLARATION OF COPY CONSTRUCTOR

 

In the above diagram Object1 of class Abc is created which is invoking parameterized constructor .Another object object2 of class Abc is created which is a copy of object1.

In order to create a copy of any object you has to use that object in argument-list of a new object.If you have not defined  a copy constructor,a compiler will automatically make it.Otherwise you can define copy constructor of your own.

DEFINITION OF COPY CONSTRUCTOR

1.Declaration of copy constructor:Firstly we declared a copy constructor by creating second object,object2 which is copy of object1 ,since we made copy of object1, we will include object1 in object2(arument_list) i.e classname object2(object1);

2.Definition of copy constructor:  We till now are having 2 objects or two constructor will be invoked when an object is created one is parameterized and second is copy constructor,so there should be 2 definitions of constructor.

  • Parameterized constructor definition: It will be same as we discussed earlier,which  will consists of argument when object is declared.
  • Copy constructor definition: In copy constructor definition, we will have a reference object in the argument of copy constructor.

Abc(Abc &object)   //reference object
{cout<<“copy constructor called”;
a=object.a;
b=object.b;
}


As in parameterized constructor we initialized  values of x and y to a and b data members.In copy constructor we will initialize the same values of a and b to  a and b using object .

KEY POINTS OF COPY CONSTRUCTOR

1.We cannot pass an argument by value in copy constructor.a reference variable has been used as an argument to the copy constructor.

2.If you have not defined copy constructor,compiler will define by its own.

3. Copy constructor is a constructor that creates a new object using an existing object of the same class.

 

Program:A programming example  to initialize values of data members using copy constructor.

#include<iostream>
using namespace std;
class Abc
{private:
int a,b;
public:            

Abc(int x, int y)
{cout<<"parametrized constructor called "<<endl;
a=x;
b=y;
}
Abc(Abc &object)
{cout<<"copy constructor called "<<endl;
a=object.a;
b=object.b;
}
void displaydata()
{cout <<"the value of a and b is" <<a<<endl<<b<<endl;
}
};
int main()
{Abc obj(4,6);//1st call implicit call
Abc obj1(obj);//copy constructer called
Abc obj2=obj;//copy constructor called again.
obj.displaydata();
obj1.displaydata();
obj2.displaydata();
return 0;
}

4.Dynamic constructors.

Dynamic constructors are used to allocate memory to objects at run-time rather i.e allocating memory to objects when they are created.

“ALLOCATION OF MEMORY TO OBJECT CAN BE DONE AT THE TIME OF OBJECT CREATION USING NEW OPERATOR IS CALLED DYNAMIC INITIALIZATION OF AN OBJECT.”

Memory allocation can be done as:

 

In this diagram:

name: is data member of class Abc

Abc(char *s) is a constructor where a string pointer of name s is created in arguments.

length is a data member of class Abc

name-new char[length] is used to assign new memory to name string.

 

  • Initialization of Data members of the object at run time  after  their initialization can be done only by dynamic constructor.
  • Dynamic constructors are used to save memory.
  • new operator is used to initialize new memory.
  • delete operator is used to deallocate memory or delete memory,so that same memory can be used by another data member.
  • Dynamic constructor are best used when we array using array and string data type.

Program:A C++ program to initialize memory of an object at run time using dynamic constructor.

#include <iostream>
using namespace std;
class Dynamic
{
 int *p;
 public:
 Dynamic()
 {
  p=new int;
  *p=10;
 }
 Dynamic(int v)
 {
  p=new int;
  *p=v;
 }
 int dis()
 { 
 return(*p);
 }
};
 
int main()
{
Dynamic obj, obj1(9);
cout<<"The value of object o's p is:";
cout<<obj.dis();
cout<<"nThe value of object 01's p is:"<<obj1.dis();
return 0;
}

 

This program illustrates allocating memory at run time  to data member (name) which is of string type using new operator.

#include<iostream>
//#include<conio.h>
#include<string.h>
using namespace std;
class Abc
{char *name;
int length;
public:
Abc(char *s)  //dynamic constructor
{
length=strlen(s);
name=new char[length];//assigning new memory at run time
strcpy(name,s);
}
void show() 
{cout<<"NAME IS:->"<<name<<endl;
cout<<"Length is:->"<<length<<endl;
 }
 };
int main()
 { char *first="ABCDEFG"; 
Abc  n1(first), n2("Hello"), n3("xyz"); 
n1.show();
n2.show();
n3.show();
//getch()
return 0;
 } 

CONSTRUCTOR OVERLOADING.

Constructor  overloading is as similar as Function Overloading where we can have multiple functions with same name  but its arguments and data type should be different.Constructor overloading is a concept  which allows class to have more than one constructors in a class.i.e in a single class you can have Default constructor,Parameterized constructor, and copy constructor as well.

Program:A programming example of c++ to find area using Constructor Overloading.

#include<iostream>

using namespace std;
class Abc
{private:
int a,b;
public:
void displaydata()
{cout <<"the value of a and b is" <<a<<endl<<b<<endl;
}
Abc()
{a=0;
b=0;
}
Abc(int x,int y)
{cout<<" parameterized constructor called  "<<endl;
a=x;
b=y;
}
Abc(Abc &A)
{cout<<" copy constructor called  "<<endl;
a=A.a;
b=A.b;
}
Abc(int x)
{cout<<" parameterized constructor called  "<<endl;
a=x;
cout<<"value of x is "<<a<<endl;
}
void square()
{cout<<"Area of square is "<<a*a<<endl;
}
};
int main()
{Abc obj(4,6);//object created of parametized constructor with 2 arguments
Abc obj1(obj);//object created of copy constructor
Abc obj2(8);//object created of parametized constructor with 1 argument.
Abc obj3;//object created of default constructor
obj.square();//normal member function is called by obj 
obj.displaydata();
obj1.displaydata();//normal member function is called by obj1
obj2.displaydata();//normal member function is called by obj2
return 0;
}

Leave a Comment