Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Type of Constructor in C++

Last Updated on September 22, 2023 by Prepbytes

Constructors serve as the building blocks of object creation in C++. They initialize the object’s attributes and prepare it for use. C++ offers various types of constructors, each with distinct roles and functionalities. This article dives into the world of Types of constructors in C++, with a focus on parameterized constructors. We’ll explore the syntax of constructors in C++, the significance of parameterized constructors, and how different constructor types enhance the flexibility and efficiency of C++ programming.

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 in C++

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 C++
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 in C++

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 parameterized constructor in C++. 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 parameterized constructor in c++ you can pass the parameter in the same way as 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 in C++.

Example of Parameterized Constructor in C++
In this section, we will learn by seeing an example of a 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
C++ constructors play a pivotal role in object-oriented programming, allowing us to create and initialize objects efficiently. Understanding the types of constructors available, especially parameterized constructors, empowers developers to tailor object creation to specific needs. By leveraging this knowledge, you can enhance code readability, promote reusability, and streamline the initialization process. As you delve into the vast landscape of C++, remember that constructors are your allies in crafting robust and well-structured programs.

FAQ: Types of Constructor in C++

Here are some FAQs related to the Types of Constructor in C++.

Q1: What is a constructor in C++?
A constructor is a special member function that is automatically called when an object of a class is created. It initializes the object’s attributes and sets it up for use.

Q2: What are the types of constructors in C++?
C++ offers several types of constructors:

  • Default Constructor: Initializes object attributes with default values.
  • Parameterized Constructor: Accepts parameters to initialize attributes with custom values.
  • Copy Constructor: Creates a new object by copying the attributes of another object.
  • Constructor Overloading: Defines multiple constructors with different parameter lists.

Q3: What is a parameterized constructor?
A parameterized constructor is a constructor that accepts parameters, allowing you to initialize object attributes with custom values during object creation.

Q4: How is a parameterized constructor invoked?
A parameterized constructor is invoked when an object of the class is created using the new keyword, and arguments are passed to the constructor that match its parameter list.

Q5: How does a parameterized constructor differ from a default constructor?
A parameterized constructor accepts parameters and initializes attributes with specific values passed as arguments. A default constructor has no parameters and initializes attributes with default values.

Q6: Can a class have multiple constructors?
Yes, a class can have multiple constructors, a concept known as constructor overloading. Each constructor can have a different parameter list, allowing flexibility in object initialization.

Q7: When should I use a parameterized constructor?
Parameterized constructors are useful when you want to provide flexibility in initializing object attributes with values tailored to the specific instance being created.

Leave a Reply

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