Type of Constructor in C++

In this blog, we will learn about constructor in c++, their meaning and code, initialization, general syntax with types of constructors in c++, and their proper explanations followed by examples of each and their code and explanation of the same. We will learn all about constructors in c++ and all of the types like copy constructor in c++ with proper explanation.

What is Constructor in C++?

A constructor in c++ is a special type of method or member function that is called automatically at the time of object creation. You can refer object as the instance of the class. Its main purpose is to initialize the object with values that are specified by the user at the time of creation and if the user doesn’t specify any value at the time of creation then it will assign or initialize the object with default values.

The constructor has the same name as that of the class name which is defined or mentioned by the user as this name is used by the compiler to have a distinguishing feature between constructor in c++ and other functions of the class.

The constructor does not have any return type nor data type or void. We can define them either outside or inside the class definition. We do not need to call the constructor in c++ specifically as it is called automatically whenever an object is created. It is known as a constructor in c++ because it constructs the values.

Syntax of Constructor in C++

The constructor can have a general syntax but it can change according to its declaration position whether that is inside the class or outside the class.

When declaring inside the class

Below is the syntax of the constructor when declaring the constructor in c++ inside the class.

(list of parameters);

We just have to write the class name as both the class name and constructor name are the same and in the parentheses the list of all the parameters of which we have to initialize or change the values.

Example
The below is the example of the above syntax.

// defining the constructor within the class

#include <iostream>
using namespace std;

class student {
    char name[10];
    int rno;
    double fee;

public:
    student()
    {
        cout << "Enter the Name:";
        cin >> name;
        cout << "Enter the RollNo:";
        cin >> rno;
        cout << "Enter the Fee:";
        cin >> fee;
    }

    void display()
    {
        cout << endl << name << "\t" << rno << "\t" << fee;
    }
};

int main()
{
    student s; // constructor gets called automatically when
            // we create the object of the class
    s.display();

    return 0;
}

Output

Enter the Name:Enter the RollNo:Enter the Fee:
Naman   35  25000

Explanation of the above example
In the above example the constructor is created inside the class and hence is initiated with default values.

When declaring Outside the class

Below is the syntax of the constructor when declaring the constructor in c++ outside the class.

:: (list of parameters){
//definition of constructor }

In the syntax shown above first, we have written the class name that will show or point us to the class to which the constructor in c++ belongs. After that, we use the scope resolution operator and the rest is the general syntax of the constructor.

Code Implementation:

// defining the constructor outside the class

#include <iostream>
using namespace std;
class student {
    char name[50];
    int rno;
    double fee;

public:
    student();
    void display();
};

student::student()
{
    cout << "Enter the Name:";
    cin >> name;
    
    cout << "Enter the RollNo:";
    cin >> rno;

    cout << "Enter the Fee:";
    cin >> fee;
}

void student::display()
{
    cout << endl << name << "\t" << rno << "\t" << fee;
}

int main()
{
    student s;
    s.display();

    return 0;
}

Output:

Enter the Name:Enter the RollNo:Enter the Fee:
Hello   78  27000

Explanation of the above code
As you can see we have declared the constructor in c++ outside the class and hence followed the above syntax.

Types of Constructors in C++

Default Constructor

The default constructor in c++ is the basic and most commonly used constructor it does not contain any arguments and is invoked or called at the time of object creation. We can either specify the default constructor or it will be automatically called at the time of object creation.

Example of Default Constructor
In this section, we will see an example of a default constructor in c++ with code, output, and proper explanation.

Code Implementation:

#include <iostream>  
using namespace std;  
class Developer  
 {  
   public:  
        Developer()    
        {    
            cout<<"Default Constructor Invoked"<<endl;    
        }    
};  
int main(void)   
{  
    Developer d1; //creating an object of Developer   
    Developer d2;   
    return 0;  
}

Output

Default Constructor Invoked
Default Constructor Invoked

Explanation of the above code
As you can see in the above code we have declared a default constructor of name developer inside the class developer and when we declare the object the default constructor is called as we have created the object hence the default constructor in c++ is appearing twice in the output.

Parameterized Constructor

It is not the compulsion that we cannot pass the arguments to the constructor in c++. We can pass the arguments to constructor in c++ and these types of constructor are known as parametrized constructor. We can pass these arguments for object initialization during the creation of the object. There is not much difference in passing the parameters to the parametrized constructor in c++ you can pass the parameter in the same way as that passing the arguments to any function. We have to define the parameterized constructor in c++ explicitly it will not be called by default.

We can have more than one parameterized constructor.
Example of Parameterized Constructor in C++
In this section, we will learn by seeing an example of parameterized constructor in C++ with code, output, and explanation.

Code Implementation:

#include<bits/stdc++.h>
using namespace std;

class Wall {
  private:
    int length;
    int height;

  public:
    Wall(int len, int hgt) {
      length = len;
      height = hgt;
    }

    int calculateArea() {
      return length * height;
    }
};

int main() {
  Wall wall1(22, 44);
  Wall wall2(6, 8);

  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

Output
Area of Wall 1: 968
Area of Wall 2: 48

Explanation of the above example
In the above example we are trying to find the area of the wall and we are passing the parameters while creating the object and in the parametrized constructor we are initializing the object values with he user-defined values and after that performing the function to calculate the area of the wall.

Copy Constructor in C++

As the name suggests the word copy constructor in c++ is used to create a copy or to initialize the object with the help of the already existing or created object.

In simple words, it is used to copy one object to another object. It is on the user to either define the default constructor or to write the default constructor in c++ explicitly.

But the copy constructor in c++ works only in the case when we declare the constructor explicitly and it is advised to always declare the constructor explicitly.

It will take the reference of the object and the object must be of the same class itself in which the copy constructor is defined.

Example(Example &t)
          {
                     id=t.id;
          }

Example of Copy Constructor in C++
In this section, we will look at the copy constructor in C++ example, The copy constructor is a very essential type of constructor in c++ and is used in many cases by the programmer. We have shown the example of copy constructor in c++ with code and explanation.

Code Implementation:

#include <bits/stdc++.h>
using namespace std;

class Wall {
  private:
  int length;
    int height;

  public:

    Wall(int len, int hgt) {
      length = len;
      height = hgt;
    }

   
    Wall(Wall &obj) {
      length = obj.length;
      height = obj.height;
    }

    double calculateArea() {
      return length * height;
    }
};

int main() {
  Wall wall1(22, 21);

  Wall wall2 = wall1;

  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

Output

Area of Wall 1: 462
Area of Wall 2: 462

Explanation of the above Code
In the above example we have a class named wall and in the class, we have a parameterized constructor with the same name itself that is initializing the value of the object below we have created the object with the help of parameterized constructor and the second object we have created with the help of copy constructor in c++.

Destructor

When an object of a class exits its scope or the delete expression is applied to a reference to an object of that class, the class’s destructor, a specific member function, is called.
A destructor can neither take nor return any parameters and will have the exact same name as the class prefixed with a tilde (). Before exiting a program, shutting files, releasing memory, and other resources can be released with the destructor.

General Syntax

:: ~ (){}

It is represented with a negation before the name of the destructor rest is the same as that of the constructor.

Example of Destructor in C++
In this section, we will look at the example of destructor with code and its explanation.

#include<bits/stdc++.h>
using namespace std;

class Exam {
public:
    Exam() { cout << "\n Constructor executed"; }

    ~Exam() { cout << "\n Destructor executed"; }
};
main()
{
    Exam t;

    return 0;
}

Output

Constructor executed
Destructor executed

Explanation of the above Example
In the above example we have created a class with the name Exam and the corresponding constructor and destructor with the same name and hence the output shows that both of them are called.

Conclusion
In the above article we have studied constructors in c++ with examples, and syntax, followed by types of constructors like default, parameterized, and copy constructors in c++ with their code, output, and explanation of the code. At last, we have discussed destructors with their overview and code with an explanation.

Leave a Reply

Your email address will not be published. Required fields are marked *