Categories: C++

Constructors and Destructors in C++

Constructor:
  • A constructor is a special member function of a class and shares the same name as of class, which means the constructor and class have the same name.
  • The compiler calls the constructor whenever a class object is created; it allocates memory to the object and initializes class data members with default values or values passed by the user when creating an object.
  • Constructors have no return type because their only task is to create and initialize an object.
Syntax of defining a constructor:
class class_name  
{  
//Statements 
public  
class_name ([parameter list])  
{  
  //Constructor's Body 
}  
};  
Types of Constructors :

There are four types of constructors in c++

  • Default constructor
  • Parameterized constructor
  • Copy Constructor
  • Dynamic Constructor
Default constructor:
  • Default constructor is also known as a zero-argument constructor, as it doesn’t take any parameter.
  • If the user does not define it, the compiler creates it on his own.
  • The default constructor always initializes data members of the class with the same value they were defined.
Example:
#include <iostream>
using namespace std;

class Student{
  
  // declaring private class data members 
private:
  string name;
  int age;
  
public: 

  // declaring constructor
  Student()
  {
      cout<<"Default constructor is called"<<endl;
      name = "student";
      age = 12;
  }
  
  // display function to print the class data members value 
  void display()
  {
      cout<<"Name of current object: "<<name<<endl;
      cout<<"Age of current object: "<<age<<endl;
  }
  
};
int main() 
{
    // creating object of class using default constructor
    Student obj;
    
    // printing class data members 
    obj.display();
    
    return 0;
}
Output:
Default constructor is called
Name of current object: student
Age of current object: 12
Parameterized constructor:
  • Parameterized constructor is used to initialize data members with user-supplied values.
  • This constructor is essentially a more advanced version of the default constructor.
  • We can define multiple parameterized constructors based on the needs of the user, but we must adhere to the rules of function overloading.
Example:
#include <iostream>
using namespace std;

class Student{
  
  // declaring private class data members 
private:
  string name;
  int age;
  
public: 

  // declaring constructor
  Student(string n, int a)
  {
      cout<<"Default constructor is called"<<endl;
      name = n;
      age = a;
  }
  
  // display function to print the class data members value 
  void display()
  {
      cout<<"Name of current object: "<<name<<endl;
      cout<<"Age of current object: "<<age<<endl;
  }
  
};
int main() 
{
    // creating object of class using default constructor
    Student obj("Rabecca",15);
    
    // printing class data members 
    obj.display();
    
    return 0;
}
Output:
Default constructor is called
Name of current object: Rabecca
Age of current object: 15
Copy Constructor:
  • A copy constructor is used when we have an object of a class and want to create a copy of it in a new declared object of the same class.
  • The compiler provides a default copy constructor for each class, and users can define their own.
  • It only accepts one argument, which is an object of the same class.
Example:
#include <iostream>
using namespace std;

class Student{
  
  // declaring private class data members 
private:
  string name;
  int age;
  
public: 

  // declaring constructor
  Student(string n, int a)
  {
      cout<<"Default constructor is called"<<endl;
      name = n;
      age = a;
  }
  Student(const Student& obj)
  {
      cout<<"Copy constructor is called"<<endl;
      name = obj.name;
      age = obj.age;
  }
  // display function to print the class data members value 
  void display()
  {
      cout<<"Name of current object: "<<name<<endl;
      cout<<"Age of current object: "<<age<<endl;
  }
  
};
int main() 
{
    // creating object of class using default constructor
    Student obj("Rabecca",15);
    
    // printing class data members 
    obj.display();
    Student obj2(obj);
    
    // printing class data members 
    obj.display();
    
    return 0;
}
Output:
Default constructor is called
Name of current object: Rabecca
Age of current object: 15

Copy constructor is called
Name of current object: Rabecca
Age of current object: 15
Dynamic Constructor:
  • The constructor is known as a dynamic constructor when memory is allocated dynamically to data members at runtime using a new operator.
  • The only difference between this constructor and the default or parameterized constructor is that it uses a new operator to allocate memory.
Example:
#include <iostream>
using namespace std;

class Student{
  
  // declaring private class data members 
private:
  int* age;
  
public: 
  Student(int* Student_age)
  {
      cout<<"Constructor for age is called"<<endl;
      
      // allocating memory 
      age = new int;
      age = Student_age;
  }
  
  // display function to print the class data members value 
  void display()
  {
      cout<<"Age of current object: "<<*age<<endl;
      cout<<endl;
  }
  
};
int main() 
{
    // creating objects of class using parameterized constructor
    int age = 25;
    Student obj1(&age);
    
    // printing class data members for first object 
    obj1.display();
    
    return 0;
}
Output:
Constructor for age is called
Age of current object: 25
Destructors:
  • The destructor function is the inverse of the constructor.
  • The compiler calls a destructor when an object is destroyed, and its main function is to deallocate the object’s memory.
  • When the program terminates, the object is destroyed, or local objects of the function exit the scope when the function terminates, or in any other case.
  • Destructors have the same properties as constructors and cannot be overloaded like constructors.
  • Destructors accept no arguments and have no return type or value.
Syntax for Destructor:
class class_name  
{  
//Statements 
public  
~class_name ([parameter list])  
{  
  //Destructor's Body 
}  
};  
Example:
#include <iostream>
using namespace std;

class Student{
  
  // declaring private class data members 
private:
  string name;
  int age;
  
public: 

  // declaring constructor
  Student()
  {
      cout<<"Default constructor is called"<<endl;
      name = "student";
      age = 12;
  }
  ~Student()
  {
      cout<<"Destructor is called"<<endl;
      name = "student";
      age = 12;
  }
  
  // display function to print the class data members value 
  void display()
  {
      cout<<"Name of current object: "<<name<<endl;
      cout<<"Age of current object: "<<age<<endl;
  }
  
};
int main() 
{
    // creating object of class using default constructor
    Student obj;
    
    // printing class data members 
    obj.display();
    
    return 0;
}
Output:
Default constructor is called
Name of current object: student
Age of current object: 12
Destructor is called

Note: also read about Function Overloading in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago