1. Introduction to C++: A Comprehensive Guide with Code Examples - 2023 2. Mastering Data Types in C++: A Comprehensive Guide with Codes and Examples (2023) 3. Learn About Variables and Types of Variables in C++ | Codzify.com 4. Control Statements in C++: A Comprehensive Guide for 2023 5. C++ Tutorial: Understanding Switch Statements with Codes and Examples in 2023 6. Understanding Memory Allocation and Pointers in C++: A Beginners Guide 7. Functions in C++ 8. Call by value and Call by Reference in C++ in depth 9. Array in C++ 10. 2d arrays in C++ 11. Classes and Objects in C++ 12. Static Functions in C++ 13. Constructors and Destructors in C++ - A Complete Guide with Examples 14. Mastering Copy Constructor in C++ - Shallow vs Deep Copy with Examples | Codzify 15. Understanding Friend Functions in C++ Made Simple! 16. Inline Functions in C++ 17. this Pointer in C++ 18. Mastering Inheritance in C++: Types and Examples Explained 19. Types of Inheritance in C++ 20. Polymorphism in C++ Explained with Codes and Examples in 2023 21. Templates in C++ 22. Getting the Value of a MultiMap in C++: Step-by-Step Guide with Examples 23. Multimap Find and Replace Operator in C++: Step-by-Step Guide - Codzify Topics 24. Exploring the Next_Permutation Algorithm without STL in C++ - Codzify Topics 25. C++ - The Difference Between Map and HashMap in STL 26. Updating Values in a std::multimap in C++ - Codzify Topics 27. Which data structure sorts the elements on insertion in C++ STL? 28. Can we implement Red Black Tree in c++ by STL containers? 29. How to Dynamically Declare an Array of Objects with a Constructor in C++ - A Step-by-Step Guide 30. What is the difference between a pointer and an object in C++? 31. Mastering Red-Black Trees with STLs Internal Implementation: A Step-by-Step Guide

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++.

Explore Codzify Courses

PREMIUM

Learn to create the Dating App using No-Code Tool FlutterFlow

Level: Advanced

Course Fees: INR 1299/-

Apply Coupon Code: UNLOCK

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Flutter Mobile App Development Course

Level: Intermediate

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

The Complete Angular Course

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Dart Programming for Absolute Beginners

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Coming Soon
FREE

Next.js course

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Fundamentals of Computer Programming Languages

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Learn HTML, CSS & Bootstrap

Level: Beginners

Course Fees: FREE

Start Watching

Latest Web Stories

1

Learn how to open WhatsApp using FlutterFlow | Step by Step Guide

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

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer