Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Constructor?
3.
Special Characteristics of Constructors
4.
Types of Constructors
4.1.
Default constructor
4.2.
Parameterized constructor
4.3.
Copy constructor 
5.
What is a Destructor?
6.
Frequently asked questions 
7.
Key Takeaways
Last Updated: Mar 27, 2024

Constructors and Destructors

Introduction

In C++, we have classes that act as a blueprint from which objects are created. The process of creating and deleting objects in C++ is a vital task. C++ provides special member functions known as a constructor, which enables an object to be initialized at the time of its creation. A constructor is also called the automatic initialization of objects.

There is another member function called destructor, which is used to destroy the objects when they are no longer required. They are used to free or release the memory occupied by the objects.

Also see, Literals in C.Fibonacci Series in C++

What is a Constructor?

A constructor is a special member function of a class, and they are used to initialize the objects of the class. Constructors are called each time an instance of a class is created. It is known as a special member function of a class as the name of the constructor is the same name of the class. A constructor basically gives value to data members of the class, these initial values can be passed as arguments to the constructor when an object is declared.

Special Characteristics of Constructors

 

  • Constructors should be declared under the public access specifier.
  • Constructors don't have any return type.
  • They can have default arguments.
  • Constructors get invoked automatically when objects are created.
  • Constructors do not get inherited, but the derived class can call the base class constructor.

Types of Constructors

There are three types of constructors in C++:

Default constructor

A constructor is said to be a default constructor if it doesn't take any arguments, that is, it has no parameter. A default constructor is automatically provided by the compiler if we do not provide it explicitly.

 

Example

#include <iostream>
using namespace std;

class student
{
public:
    int age;
    string name;
    // Default Constructor
    student()
    {
        age = 10;
        name = "xyz";
    }
};

int main()
{
    // Default constructor called automatically
    // when the object is created
    student std1;
    cout << "age: " << std1.age << endl
        << "name: " << std1.name;
    return 1;
}


Output

age: 10
name: xyz

 

You practice by yourself with the help of online c++ compiler.

Parameterized constructor

A constructor is called a parameterized constructor if that constructor can accept arguments. Arguments help to initialize the objects when they are created. Like we pass arguments to a normal function the same way arguments are passed to the parameterized constructor. The arguments passed are used to initialize the objects in the constructor’s body.
 

When an object is declared using the parameterized constructor, the initial values have to be passed as arguments to the constructor. Constructors can be called implicitly or explicitly.  

 

Student s= Student(0,10);  // Explicit call
Student s(0,10);  // Implicit call 

 

Example

#include <iostream>
using namespace std;

class student
{
public:
    int age;
    string name;

    // Parameterized Constructor
    student(int x,string y)
    {
        age = x;
        name = y;
    }
};

int main()
{
    //Constructor called
    student std1(10,"xyz");
    cout << "age: " << std1.age << endl
        << "name: " << std1.name;
    return 1;
}

 

Output

age: 10
name: xyz

 

Copy constructor 

A constructor is called a copy constructor, which initializes an object using another object of the same class. We need a copy constructor when an object of the class is returned by values, or it is passed by value as an argument. If we don't define a copy constructor explicitly, then the C++ compiler creates a default constructor for each class which does a memberwise copy between objects.

 

Example

#include<iostream>
using namespace std;

class Student
{
private:
    int age, marks;
public:
    Student(int x, int y) { age = x; marks = y; }

    // Copy constructor
    Student(const Student &std1) {age = std1.age; marks = std1.marks; }

    int getAge()            {  return age; }
    int getMarks()            {  return marks; }
};

int main()
{
    Student std1(10, 85); // Normal constructor is called here
    Student std2 = std1; // Copy constructor is called here

    // Let us access values assigned by constructors
    cout << "Student-1 age = " << std1.getAge() << ", Student-1   marks = " << std1.getMarks();
    cout << "\nStudent-2 age = " << std2.getAge() << ", Student-2 marks = " << std2.getMarks();

    return 0;
}

 

Output

Student-1 age = 10, Student-1 marks = 85
Student-2 age = 10, Student-2 marks = 85

What is a Destructor?

A destructor is a member function which is used to destroy the objects created by constructors. Destructor has the same name as the class name preceded by ‘~’ tilde operator. It deallocates the memory of the object. A destructor is usually called when the object of the class is freed or deleted. A destructor can not be overloaded. They are always called in the reverse order of the constructor, that is, if a class is inherited by another class, then first the destructor of the child class is called and then the destructor of the parent class. A destructor doesn't take any argument or return any value.
 

Example

#include <iostream>
using namespace std;

class X
{
public:
    // constructor
    X()
    {
        cout<<"Constructor called"<<endl;
    }

    // destructor
    ~X()
    {
        cout<<"Destructor called"<<endl;
    }
};

int main()
{
    X x;   // Constructor Called
} //  Destructor called for x

 

Output

Constructor called
Destructor called

 

Know What is Object in OOPs here in detail.

Frequently asked questions 

Ques: Can a constructor be overloaded?

Ans: In C++, we can have more than one constructor in a class with the same name, as long as each has a different list of arguments, which is known as constructor overloading.

Ques: Is destructor overloading possible in C++?

Ans: No, it is not possible to overload destructors in C++.

Ques: What happens if we don't explicitly define a constructor and a destructor?

Ans: if we don't explicitly define a constructor and a destructor, then the compiler automatically defines a constructor and destructor for the user automatically.

Key Takeaways

In this blog, we have covered the following topics:

  • Firstly, we discussed what constructors are, why we use them, and what are the different types of constructors in C++ with examples.
  • Then we discussed what destructors are and how to use them.

Constructors and destructors are used in classes that help us to implement the concepts of object-oriented programming. You can study more about object-oriented programming from this

Live masterclass