Constructors and Destructors in C++ - A Complete Guide with Examples

Article by: Manish Methani

Last Updated: October 18, 2021 at 10:04am IST
5 min 40 sec read

Introduction to Constructors and Destructors in C++:

In C++, constructors and destructors are two special member functions that are used to initialize and clean up the objects of a class. Constructors are called when an object is created, while destructors are called when an object is destroyed. Constructors initialize the data members of a class, and destructors clean up any resources allocated by the object. In this tutorial, we will discuss constructors and destructors in detail and provide examples of their usage.

Constructors in C++:

Constructors are of four types in C++: default constructor, parameterized constructor, copy constructor, and constructor overloading.

Default Constructors in C++:

A default constructor is a constructor that takes no arguments. It is called when an object of the class is created with no arguments. The default constructor initializes the data members of the class to their default values.

Example 1: Default Constructor

    #include<iostream>
    using namespace std;
    
    class MyClass {
       public:
          MyClass() {
             cout<<"Default constructor called"<<endl;
          }
    };
    
    int main() {
       MyClass obj;
       return 0;
    }
    

Output:

Default constructor called

Parameterized Constructors in C++:

A parameterized constructor is a constructor that takes one or more arguments. It is used to initialize the data members of the class with the values passed as arguments. The parameters of a constructor are used to set the values of the data members.

Example 2: Parameterized Constructor

#include<iostream>
using namespace std;

class MyClass {
   public:
      MyClass(int val1, int val2) {
         member1 = val1;
         member2 = val2;
      }
      void display() {
         cout<<"Member 1:"<<member1<<endl;
         cout<<"Member 2:"<<member2<<endl;
      }
   private:
      int member1;
      int member2;
};

int main() {
   MyClass obj(10, 20);
   obj.display();
   return 0;
}

Output:

Member 1: 10
Member 2: 20

Copy Constructors in C++:

A copy constructor is a constructor that is used to create a new object from an existing object of the same class. It is called when an object is created using the assignment operator or when an object is passed as an argument to a function.

Example 3: Copy Constructor

    #include<iostream>
using namespace std;

class MyClass {
   public:
   MyClass(int val1, int val2) {
    member1 = val1;
    member2 = val2;
 }
      MyClass(const MyClass &obj) {
         member1 = obj.member1;
         member2 = obj.member2;
      }
      void display() {
         cout<<"Member 1:"<<member1<<endl;
         cout<<"Member 2:"<<member2<<endl;
      }
   private:
      int member1;
      int member2;
};

int main() {
   MyClass obj1(10, 20);
   MyClass obj2 = obj1;
   obj2.display();
   return 0;
}

Output:

    Member 1: 10
    Member 2: 20

Constructor Overloading in C++:

Constructor overloading is a technique in C++ that allows you to define multiple constructors for a class. Each constructor can have a different number of parameters or different types of parameters. When an object of the class is created, the appropriate constructor is called based on the arguments passed to it.

Example 4: Constructor Overloading

    #include<iostream>
using namespace std;

class MyClass {
   public:
      MyClass() {
         member1 = 0;
         member2 = 0;
      }
      MyClass(int val) {
         member1 = val;
         member2 = val;
      }
      MyClass(int val1, int val2) {
         member1 = val1;
         member2 = val2;
      }
      void display() {
         cout<<"Member 1:"<<member1<<endl;
         cout<<"Member 2:"<<member2<<endl;
      }
   private:
      int member1;
      int member2;
};

int main() {
   MyClass obj1;
   MyClass obj2(10);
   MyClass obj3(10, 20);
   obj1.display();
   obj2.display();
   obj3.display();
   return 0;
}

Output:

Member 1: 0
Member 2: 0
Member 1: 10
Member 2: 10
Member 1: 10
Member 2: 20

Destructors in C++:

A destructor is a special member function of a class that is called when an object of the class is destroyed. It has the same name as the class with a tilde (~) symbol in front of it. The destructor is used to free up any resources that were allocated to the object during its lifetime.

Example 5: Destructor

    #include<iostream>
using namespace std;

class MyClass {
   public:
      MyClass() {
         cout<<"Constructor called"<<endl;
      }
      ~MyClass() {
         cout<<"Destructor called"<<endl;
      }
};

int main() {
   MyClass obj;
   return 0;
}

Output:

Constructor called
Destructor called

Frequently Asked Questions

Q1. What is the purpose of constructors in C++?

A1. Constructors are used to initialize the data members of a class when an object of the class is created.

Q2. What is a default constructor in C++?

A2. A default constructor is a constructor that takes no arguments.

Q3. What is a parameterized constructor in C++?

A3. A parameterized constructor is a constructor that takes one or more arguments.

Q4. What is a copy constructor in C++?

A4. A copy constructor is a constructor that creates a new object as a copy of an existing object.

Q5. What is constructor overloading in C++?

A5. Constructor overloading is a feature in C++ that allows a class to have multiple constructors with different parameter lists.

Q6. What is the syntax of a constructor in C++?

ClassName::ClassName() {
            // Constructor code here
         } 

Q7. What is the syntax of a destructor in C++?

ClassName::~ClassName() {
            // Destructor code here
         }
          

Q8. What is the difference between a constructor and a destructor in C++?

A8. A constructor is called when an object of a class is created, whereas a destructor is called when an object is destroyed.

Q9. Why are constructors and destructors important in C++?

A9. Constructors and destructors are important in C++ because they help to ensure that objects are properly initialized and cleaned up, which helps to prevent errors and memory leaks.

Q10. Can a class have more than one destructor in C++?

A10. No, a class can only have one destructor in C++.

Q11. What happens if a constructor throws an exception in C++?

A11. If a constructor throws an exception in C++, the object is not created and any resources that were allocated before the exception occurred are automatically cleaned up.

Q12. Can constructors be virtual in C++?

A12. Yes, constructors can be virtual in C++, but it is generally not recommended because it can lead to confusing and unexpected behavior.

Q13. Can a destructor be overloaded in C++?

A13. No, a destructor cannot be overloaded in C++.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test
include_once 'codzify-footer.php'; ?>