Topic :Class Constructor & Destructor: Defining Constructor | Type of Constructor | Destructor

Constructor:

Constructor is a special method of a Class which will invoke Automatically whenever the object of Class is created. Constructors are Responsible for Object Initialization and Memory Allocation of its class. If we create any Class without the constructor, the compiler will automatically create the one default constructor for that class. The default Constructor Will Not perform any Initialization. So we need to create our Own Constructor for Initialization.



Why we Need Constructor?

int x;

When We Declare an variable of type integer, and then ask to print it's value. The Answer will be something else, something like garbage, because we Never initialize this variable with any value. so there will some garbage value in that Memory location, so when we try to print the value of that variable, it's print that garbage value. and we don't Need any garbage in our program, so we used to initialize the variable with some value, if there is no value present, then we used to initialize the variable with 0(zero).


Student Obj;

Similarly When we create the Object of the Class, the Object will reserve some Memory and assigns a name. If we do not Initialize the Class Properties, the properties will contain some garbage values. so in order to stop that, We use constructor.



Defining Constructor:

A Constructor has exactly the same name as that of class and it does not have any return type. After Defining the Constructor, we don't need to call it in our Main() method. Because constructor will Automatically Invoked, when an Object is being created. Let's have an simple Example to know, how exactly we can create an Constructor, and how this constructor work.


/* Example -Constructor- InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Constructor
{
   private:
	//Private Members:
 
   public:
	//Public Members:
	void display()
	{
	   cout<<"Hi, did you Call Constructor?";
	}
 
	//Constructor:
	Constructor()
	{
  	   cout<<"You didn't Call be, but still am here: ";
	   cout<<"\nSurprised?"<<endl;
	}		
};
 
 
main()
{
 
   //object Creation:
   Constructor obj;	
 
   //Calling display() method:
   obj.display();
 
   return 0;
}
 


In Above Example, We just define Constructor, but we didn't Call it in our Main() Program for execution. But still its execute automatically. It is because of Object, we create an Object, so whenever we create an Object of the Class, the Constructor Called Automatically.


If we define any Constructor in our Class, then the Program will use that constructor only. Else default constructor will Work automatically.


  • Type of Constructor:

    The Default Constructor does not have Parameter or anythings. and the default constructor is not able to Initialization automatically. In Other Languages like C#, the Default Constructor Initializes all Numeric Variables in the Class to Zero, and all Other String and Object fields to NULL. But in C++, we need to create our Own constructor for doing this job. In C++, we can create four types of Constructor:
    » Default Constructor:
    » Parameterized Constructor:
    » Copy Constructor:
    » Private Constructor:



Default Constructor:

A constructor without Having any Parameters Called Default Constructor. In this Constructor, we can Initialized the Instance of the Class without any Parameters ,as shown in the given Example:


/* Example -Default Constructor- InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Def_Constructor
{
   private:
	//Private Members:
 
   public:
        //Public Members:	
       int x, y;  //public properties:
 
	//Constructor:
	Def_Constructor()
	{
	   x = 15;
	   y = 10;
	}					
};
 
 
main()
{
   //object Creation:
   Def_Constructor obj;	
 
   //Access Public properties:
   cout<<"The value of X is: "<<obj.x<<endl;
   cout<<"The value of Y is: "<<obj.y<<endl;
 
   return 0;
}
 


Parameterized Constructor:

A constructor with at Least one parameter is Called as Parameterized Constructor. In Parameterized Constructor, we can Initialize each Instance of the Class to different Values, as shown in the given example:


/* Example -Parameterized Constructor- InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Par_Constructor
{
   private:
	//Private Members:
 
   public:	
       //Private Members:
       int x, y;  //public properties:
 
       //Constructor:
	Par_Constructor(int a, int b)
	{
	   x = a;
	   y = b;
	}					
};
 
 
main()
{
    //first object creation:
    Par_Constructor obj1(12, 15);	
 
    //Access Public properties:
    cout<<"First Object:"<<endl;
    cout<<"The value of X is: "<<obj1.x<<endl;
    cout<<"The value of Y is: "<<obj1.y<<endl;
 
    //second object creation:
    Par_Constructor obj2(44, 65);	
 
    //Access Public properties:
    cout<<"\nSecond Object:"<<endl;
    cout<<"The value of X is: "<<obj2.x<<endl;
    cout<<"The value of Y is: "<<obj2.y<<endl;
 
    return 0;
}
 


Copy Constructor:

The Copy Constructor is used to creates an Object by Initializing it with an Object of the Same Class, which has been created previously. The main purpose of the copy Constructor is to initialize one object from another object of the same type. If a copy constructor is not defined in a Class, the compiler defines one itself. If class has pointer variables and has some dynamic memory allocations, then it's must to have a copy constructor.


/* Example -Copy Constructor- InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Copy_Constructor
{
   private:
	//Private Members:
 
   public:	
    //Public Members:
    int x, y;  //public properties:
 
    //Normal Constructor:
    Copy_Constructor(int a, int b)
    {
	x = a;
	y = b;
    }
 
   //Copy Constructor:
   Copy_Constructor(const Copy_Constructor &C_obj)
   {
	x = C_obj.x;
	y = C_obj.y;
   }					
};
 
 
main()
{
   //first object creation:
    Copy_Constructor obj1(12, 15);	
 
    //Access Public properties:
    cout<<"Using Normal Constructor:"<<endl;
    cout<<"The value of X is: "<<obj1.x<<endl;
    cout<<"The value of Y is: "<<obj1.y<<endl;
 
    //second object creation:
    Copy_Constructor obj2(obj1);	
 
    //Access Public properties:
    cout<<"\nUsing Copy Constructor:"<<endl;
    cout<<"The value of X is: "<<obj2.x<<endl;
    cout<<"The value of Y is: "<<obj2.y<<endl;
 
    return 0;
}
 


Private Constructor:

Private Constructor is a special Instance constructor Used in a Class to restrict object creation for all Other Classes and methods, except Friend Class. If a Class has one or more private constructor and no public constructor, then other Classes is Not Allowed to Create Object of this Class. Its mean, we can Neither create the Object of this class nor it can be inherit by other Class except Friend Class. The main purpose of Creating Private Constructor is to restrict the Class from Being instantiated when it contains every member as static.


/* Example -Private Constructor- InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class Private_Constructor
{
   friend class frnd;  //Friend class Declaration
 
   private:
	//Private constructor:
	Private_Constructor()
	{
 	   cout<<"This is private Constructor:"<<endl;
	}	
};
 
//friend Class:
class frnd
{
   //object of Private_Constructor Created:
   Private_Constructor fobj; 
   public:
   frnd()
   {
      cout<<"Friend Class:"<<endl;
   }
};
 
main()
{
   //Friend class "frnd" Object Creation:
   frnd obj1;	    
   return 0;
}
 

In Above example, we create Private Constructor. and one friend class. only friend class can invoked that private constructor.


  • More about Private Constructor:

    » Use Private constructor when we have only static Member.
    » Once we Provide a Constructor that is either private or Public or any, the compiler will not allow us to add public constructor without parameters to the class. its mean we need to overload the constructor.
    » If we want to create object of class even if we have private constructors, than we need to have public constructor along with private constructor.



Destructor:

A Destructor is a special member of a Class that calls automatically each time when an Object is Destroyed. An object is destroyed when it goes out of Scope. A Destructor has Exactly the Same name as that of the Class with a Prefixed Tilde (~) and it can neither return a value nor can take any parameters. We use Destructor to Only Releasing Memory resources Before existing the Program.


Programmers usually do not need to perform as many tasks in destructor as they do in constructors. Typically, we need code in a destructor when an object contains a pointer to a member. we don’t want to retain a pointer that holds the address of an object that has been destroyed..


The Programmer has no control on when the destructor is going to be executed because this is determined by the Garbage Collector. The Garbage Collector checks for Objects that are no longer being used by the application. It considers these objects eligible for Destruction and reclaims their memory. Destructors are also called when the program exists. Now let's have an Example, where we will see how this destructor work.


/* Example - Destructor - InfoBrother:*/
 
#include<iostream>
using namespace std;
 
class House
{
   private:
	//Private Members:
 
   public:
	//Public Members:
	House(int price) //constructor:
	{
 	   cout<<"House Created Successfully:"<<endl;
	   cout<<"Price: $"<<price<<endl;
	}
 
	~House() //Destructor:
	{
	   cout<<"Oops!! House Destroyed:"<<endl;
	}			
};
 
main()
{
   //Object Creation:
   House obj(1030000);
 
   return 0;
}
 


  • More about Destructor:

    » Destructor are Invoked Automatically, and Can't be Invoked explicitly.
    » Destructors Can't be Overloaded. thus, a Class can have at most one destructor.
    » Destructors are not inherited. Thus, a Class has no Destructors other than one, Which may be declared in it.
    » Destructors can't be used with Structs. They are only used with classes.
    » An Instance become Eligible for destruction when it is no longer possible for any code to use the Instance.
    » Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
    » A Destructor does not take Modifiers or have Parameters.



Every C++ Class object Automatically has four special Members function. a Default Constructor , a Default Destructor , an Default Assignment Operator and a Copy Constructor.
The Default Assignment Operator Allows us to assign one object to another, as in Object1 = Object2.
Copy Constructor Executes when we pass an obect as an argument to a function, making a local copy within the function.








I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement