Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of Constructors in C++
3.
Writing a Constructor Outside the Class
4.
Example
4.1.
C++
5.
Characteristics of Constructors in C++
6.
Types of Constructors in C++
6.1.
Default Constructor
6.2.
Parameterized Constructor
6.3.
Copy Constructor
6.4.
Move Constructor
7.
Destructors in C++
7.1.
What is a Destructor?
7.2.
How to Write a Destructor
7.3.
Why Use Destructors?
7.4.
Syntax of Destructors in C++
7.5.
Writing a Destructor
7.6.
What Happens in a Destructor
7.7.
Example of a Destructor in C++
7.8.
C++
7.9.
How the Destructor Works
8.
Frequently Asked Questions
8.1.
Can a class have more than one constructor?
8.2.
Is it mandatory to define a destructor in a class?
8.3.
What happens if I forget to free resources in the destructor?
9.
Conclusion
Last Updated: Apr 4, 2024
Easy

Constructor in C++

Author Riya Singh
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Constructors in C++ play a crucial role in initializing new objects, ensuring they are ready to be used from the moment they come into existence. These special member functions strictly  set initial values and perform any setup routines necessary for the objects to function optimally. 

Constructor in C++

In this article we will talk about constructors in detail. You'll learn about their syntax, various types, with proper examples. At the end we will also see how destructors works, a very important part of this routine and we will see how they are different from each other.

Syntax of Constructors in C++

To use constructors in C++, you need to know how to write them in your code. Constructors look a bit like functions, but they have specific rules.

Writing a Constructor Inside the Class:

When you write a constructor inside your class, it looks like this:

class MyClass {
public:
    MyClass() {
        // What the constructor does
    }
};


In this example, MyClass() is the constructor. It has the same name as the class and doesn't need a return type, not even void.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Writing a Constructor Outside the Class

Sometimes, you might want to write the constructor outside the class. Here's how:

class MyClass {
public:
    MyClass(); // Declaration inside the class
};

MyClass::MyClass() {
    // Definition outside the class
    // What the constructor does
}


Here, you first tell the class there will be a constructor (MyClass();), and then you define what it does outside the class (MyClass::MyClass() { ... }).

Example

Let's look at a simple example using a Book class.

Creating a Book Class with a Constructor:

Imagine we have a class named Book. We want each book to have a title and an author. Here's how we can do it:

  • C++

C++

#include <iostream>
#include <string>
using namespace std;

class Book {
public:
string title;
string author;

// Constructor for Book
Book(string bookTitle, string bookAuthor) {
title = bookTitle;
author = bookAuthor;
}
};

int main() {
// Creating a Book object
Book myBook("The Little Prince", "Antoine de Saint-Exupéry");

cout << "Book: " << myBook.title << "\n";
cout << "Author: " << myBook.author << "\n";

return 0;
}

Output

Book: The Little Prince
Author: Antoine de Saint-Exupéry


In this example, Book(string bookTitle, string bookAuthor) is the constructor. It sets up a new Book object with a title and an author.

When we create myBook, we give it a title and an author. The constructor uses these to set up myBook.

Characteristics of Constructors in C++

  • Automatic Call-: Constructors are called automatically when you create an object. You don't need to call them yourself like other functions.
     
  • No Return Type-:Constructors don't have a return type, not even void. This is because their job is to set up the object, not to give something back.
     
  • Same Name as the Class-:The constructor's name is always the same as the class name. This is how C++ knows it's a constructor.
     
  • Can't be Called Directly-:You can't call a constructor on an object that's already created. They're only for setting up new objects.
     
  • Default Constructor-:If you don't write any constructor for your class, C++ will give you a default one. This default constructor doesn't do much, just creates the object.

Types of Constructors in C++

Default Constructor

A default constructor doesn't take any arguments. It's used to create an object when you don't need to give it any initial values.

class Box {
public:
    int size;
    // Default constructor
    Box() {
        size = 10; // Giving a default size
    }
};


In this Box class, the default constructor sets every new Box object's size to 10.

Parameterized Constructor

A parameterized constructor takes arguments and uses them to set the object's initial state. This is useful when you want your object to start with specific values.

class Rectangle {
public:
    int width, height;
    // Parameterized constructor
    Rectangle(int w, int h) {
        width = w;
        height = h;
    }
};


Here, the Rectangle class has a constructor that takes width and height as parameters to set up new Rectangle objects.

Copy Constructor

A copy constructor creates a new object as a copy of an existing object. This is useful when you want two objects with the same state.

class Circle {
public:
    int radius;
    // Copy constructor
    Circle(const Circle &oldCircle) {
        radius = oldCircle.radius;
    }
};


This Circle class's copy constructor takes an existing Circle object and makes a new one with the same radius.

Move Constructor

A move constructor transfers resources from a temporary object to a new object. It's used to improve performance by avoiding unnecessary copying.

class Vector {
public:
    int size;
    int* data;
    // Move constructor
    Vector(Vector &&tempVector) : size(tempVector.size), data(tempVector.data) {
        tempVector.data = nullptr; // Prevents deleting data in the temporary object
    }
};


In the Vector class, the move constructor takes a temporary Vector object, takes over its data, and then ensures the temporary object doesn't delete the data when it's destroyed.

Destructors in C++

Just like constructors set up objects when they are created, destructors are special functions that clean up when an object is no longer needed. Here's how they work:

What is a Destructor?

A destructor is a function that is called automatically when an object goes out of scope or is explicitly deleted. Its job is to release resources that the object might have acquired during its lifetime.

How to Write a Destructor

The destructor has the same name as the class, preceded by a tilde (~). It doesn't take any arguments and doesn't return anything.

class MyClass {
public:
    // Destructor
    ~MyClass() {
        // Code to free resources or clean up
    }
};


In this example, ~MyClass() is the destructor for the MyClass class. It would contain code to free any resources that objects of MyClass might hold.

Why Use Destructors?

Destructors are essential for managing resources, especially in programs that use dynamic memory allocation. Without a destructor to free allocated memory, a program can leak memory, leading to inefficiency and potential crashes.

Destructors ensure that when your objects are done, they are cleaned up properly, making your code safer and more reliable.

Syntax of Destructors in C++

Destructors have a simple yet specific syntax in C++ to ensure they function correctly when an object's lifetime ends. 

Writing a Destructor

A destructor is declared within a class and has the same name as the class, preceded by a tilde (~). It doesn't accept any parameters and doesn't return a value.

class MyClass {
public:
    // Destructor
    ~MyClass() {
        // Actions to perform when the object is destroyed
    }
};

What Happens in a Destructor

The code inside the destructor typically includes tasks like releasing memory, closing files, or other cleanup activities. This ensures that the program doesn't leave behind any unused resources when an object is no longer in use.

Automatic Invocation:

Just like constructors, destructors are called automatically. A destructor is invoked when an object goes out of scope or is deleted. You don't need to call it manually.

Example of a Destructor in C++

Imagine we have a class called Message that dynamically allocates memory to store a text message.

Creating the Message Class:

Our Message class will have a constructor to set up the message and a destructor to clean up when the object is no longer needed.

  • C++

C++

#include <iostream>
#include <cstring> // For strcpy and strlen

using namespace std;

class Message {
char* text;

public:
// Constructor
Message(const char* msg) {
text = new char[strlen(msg) + 1]; // Allocating memory
strcpy(text, msg); // Copying the message
}

// Destructor
~Message() {
delete[] text; // Freeing the allocated memory
}

void print() {
cout << text << endl;
}
};

int main() {
Message note("Hello, C++ destructors!");
note.print();

// The destructor will be called automatically here when 'note' goes out of scope
return 0;
}

Output

Hello, C++ destructors!

How the Destructor Works

In this example, the destructor ~Message() is called automatically when the note object goes out of scope at the end of the main function.

The destructor's job here is to free the memory allocated for storing the message, preventing a memory leak.

Frequently Asked Questions

Can a class have more than one constructor?

Yes, a class in C++ can have multiple constructors, including default, parameterized, and copy constructors, to initialize objects in different ways.

Is it mandatory to define a destructor in a class?

No, it's not mandatory. If you don't define a destructor, C++ provides a default destructor that does nothing. You should define a destructor if your class allocates resources that need to be released when objects are destroyed.

What happens if I forget to free resources in the destructor?

Forgetting to free resources like dynamically allocated memory can lead to memory leaks, where memory that's no longer needed isn't returned to the system. This can reduce the available memory and potentially slow down or crash the program.

Conclusion

In this article, we've learned about constructors and destructors in C++, starting from their basic definitions and moving on to their syntax, types, and examples. Constructors are special functions that set up new objects with essential values and initial conditions, while destructors clean up by freeing resources when objects are no longer in use. Understanding and using these tools effectively can lead to more robust and efficient C++ programs. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass