Constructors and Destructors in C ++

Constructors and Destructors in C ++

21 May 2024
Advanced
3.05K Views
15 min read
Learn via Video Course & by Doing Hands-on Labs

C++ Programming For Beginners

Constructors and Destructors in C ++: An Overview

After seeing the basics of OOP concepts in C++, let us now move a step forward. In this C++ tutorial, we will look at an important OOP construct, constructors, and destructors in C++. This topic will now repeat in every OOPs tutorial in C++ like inheritance in C++, polymorphism in C++, etc. Therefore it's very important to get hold of this.For more knowledge and understanding, consider our C++ Certification Course.

What is a Constructor in C++?

A constructor in C++ is a special member function invoked automatically when an object of a class is created. It is generally used to initialize the data members of the new object. They are also used to run a default code when an object is created. The constructor in C++ has the same name as the class or structure and does not have a return value.

Syntax of a Constructor prototype

<class-name> (list-of-parameters); 

A constructor in C++ can be defined in two ways:

  • inside the class

    Syntax

    <class-name> (list-of-parameters) { 
    // constructor definition 
    } 
    

    Example

    class ScholarHat { //class
     public: //access specifier
     ScholarHat() { //constructor
     // code
     }
    };
  • outside the class using the scope resolution operator: :

    Syntax

    <class-name>: : <class-name>(list-of-parameters){ 
    // constructor definition
    } 
    

    Example

    ScholarHat: : ScholarHat() { //outside the class constructor
     // code
     }
    

Remember: The access specifier of a constructor is always public.

Read More - Advanced C++ Interview Interview Questions and Answers

Types of Constructors in C++

There are three types of constructors in C++:

  1. Default Constructor in C++
  2. Parameterized Constructor in C++
  3. Copy Constructor in C++

  1. Default Constructor in C++

It is a constructor in C++ with no parameters.

Example of C++ Default Constructor


#include <iostream> 
using namespace std; 
class Student {
public:
 Student() {
 cout << "Default Constructor Invoked" << endl;
 }
};

int main() {
 Student s1; // Creating an object of Student class
 Student s2;
 return 0;
} 

The above C++ code in C++ Online Compiler has a default constructor named Student(). When the objects s1 and s2 of the Student class is created, the constructor Student() gets invoked and prints the statement written inside it

Output

Default Constructor Invoked
Default Constructor Invoked

  1. Parameterized Constructor in C++

It is a constructor in C++ with parameters. This is the preferred method to initialize the data members of a class.

Example of C++ Parametrized Constructor


#include <iostream> 
using namespace std;
class Student {
public:
 int id; // data member (also instance variable)
 string name; // data member (also instance variable)
 float marks;

 Student(int i, string n, float m) {
 id = i;
 name = n;
 marks = m;
 }

 void display() {
 cout << id << " " << name << " " << marks << " " << endl;
 }
};

int main() {
 Student s1 = Student(101, "Urmi", 78); // creating an object of Student
 Student s2 = Student(102, "Pragati", 89);
 s1.display();
 s2.display();
 return 0;
}

Here the class Student has a parametrized constructor Student(int i, string n, float m). When the object s1 and s2 of the Student class is created, the constructor is called with arguments to initialize the data members of the class.

Output

101 Urmi 78
102 Pragati 89

Point to remember: If we have not defined a constructor in our class, then the C++ compiler will automatically create a default constructor with an empty code and no parameters.

3. Copy Constructor in C++

It is a member function that initializes the data members of an object using another object from the same class. In other words, the copy constructor in C++ is used to copy data of one object into another.

Example of C++ Copy Constructor


#include <iostream> 
using namespace std;
class Student {
public:
 int id; // data member (also instance variable)
 string name; // data member (also instance variable)
 float marks;

 Student(int i, string n, float m) { // parametrized constructor
 id = i;
 name = n;
 marks = m;
 }

 // Copy constructor with a Student object as a parameter
 // Copies data of the obj parameter
 Student(const Student& obj) {
 id = obj.id;
 name = obj.name;
 marks = obj.marks;
 }

 void display() {
 cout << id << " " << name << " " << marks << " " << endl;
 }
};

int main() {
 Student s1 = Student(101, "Urmi", 78); // Creating an object of the Student class
 Student s2 = s1; // Copy contents of s1 to s2
 s1.display();
 s2.display();
 return 0;
}

In this program, we have used a copy constructor, Student(const Student& obj) to copy the contents of one object of the Student class to another.

  • The parameter of this constructor has the address of an object of the Student class.
  • We then assign the values of the variables of the obj object to the corresponding variables of the object calling the copy constructor. This is how the contents of the object are copied.
  • The const in the copy constructor's parameter const Student& obj is used to ensure that the object being passed as an argument to the copy constructor is not modified within the copy constructor itself.
  • In main(), we then create two objects s1 and s2 and then copy the contents of s1 to s2.
  • The s2 object calls its copy constructor by passing the address of the s1 object as its argument i.e. &obj = &s1.

Output

101 Urmi 78
101 Urmi 78

Member Function vs. Constructor in C++

  • The constructor's name is the same as the class's
  • In the default type, there aren't any input parameters for the constructor. However, input parameters are available for copy and parameterized constructors.
  • There is no return type for constructors.
  • An object's constructor is invoked automatically upon creation.
  • It must be shown in the class's public space i.e. only under the public access specifier.
  • The C++ compiler creates a default constructor for the object if a constructor is not specified.

What is Destructor in C++?

Destructors in C++ are member functions in a class that deletes an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called, etc.

Destructors don’t take any argument and don’t return anything. Also, destructors have the same name as their class and their name is preceded by a tilde ~.

A destructor in C++ can be defined in two ways:

  • Inside the class

    Syntax

    ~<class-name> { 
    // destructor definition 
    } 
    

    Example

    class ScholarHat { //class
     public: //access specifier
     ~ScholarHat() { //destructor
     // code
     }
    };
  • Outside the class using the scope resolution operator: :

    Syntax

    <class-name>: : ~<class-name>(){ 
    // destructor definition
    } 
    

    Example

    ScholarHat: : ~ScholarHat() { //outside the class destructor
     // code
     }
    

Example of Destructor in C++ Compiler

 
#include <iostream>
using namespace std;

class ScholarHat {
public:
 // User-Defined Constructor
 ScholarHat() { cout << "\n Constructor executed"; }

 // User-Defined Destructor
 ~ScholarHat() { cout << "\nDestructor executed"; }
};

int main() {
 ScholarHat t;
 return 0;
} 

The above C++ program shows the order of execution of the constructor and destructor when an object is created and destroyed within the main() function. It defines a class ScholarHat with a user-defined constructor and destructor.

Output

Constructor executed
Destructor executed

Characteristics of a Destructor in C++

  • The destructor function is automatically invoked when the objects are destroyed.
  • It cannot be declared static or const.
  • The destructor does not have parameters.
  • It has no return type.
  • An object of a class with a destructor cannot become a member of the union.
  • A destructor should be declared in the public section of the class.
  • The programmer cannot access the address of the destructor.

Member Function vs. Destructor in C++

  • Destructors have the same name as the class preceded by a tilde ~.
  • Destructors don’t take any argument and don’t return anything
Summary

In this blog post, we discussed constructors and destructors in C ++. Constructors are responsible for initializing objects, while destructors are responsible for deallocating memory when an object is no longer needed. If you still have trouble understanding these concepts, enrol in ourC++ Certification.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 22 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Full Stack .Net Developer Jun 30 SAT, SUN
Filling Fast
11:00AM to 01:00PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this