Constructor in C++ | Destructor in C++

In this article, we will learn about Constructors and Destructors in C++.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Constructors in C++

When an object is created, a special member function of the class, known as constructor, is called automatically. Constructors are extremely useful for initializing class objects.

Properties of a Constructor

  • When we create an object, it is called automatically.
  • It has the same name as that of the class.
  • It has no return type.
  • It cannot be inherited, although the derived class can call it.
  • It cannot be const.
  • It cannot be virtual.
  • It must be declared inside public in a class.
  • It can have default parameters.
  • It’s address is inaccessible.

If the user does not define a constructor, the compiler implicitly generates a default constructor.

Types of Constructors in C++

1. Default Constructor in C++

A default constructor is a constructor that does not have parameters.

Syntax

class_name() {
  //statements
}

Example of default constructor in C++

#include <iostream>
using namespace std;

class Rectangle {
    public:
    float length, breadth;
    Rectangle() {           //Default Constructor
        length = 10;
        breadth = 6.5;
    }
};

int main() {
  Rectangle r;
  cout<<"length = "<<r.length<<endl;
  cout<<"breadth = "<<r.breadth;
  return 0;
}

Output

length = 10
breadth = 6.5

2. Parameterized Constructor in C++

We can also pass parameters to a constructor. A constructor that has parameters is called a parameterized constructor. These parameters are used to set initial values to the data members of an object as soon as it is created.

Syntax

class_name(parameter1, parameter2, …) {
  //statements
}

Example of parameterized constructor in C++

#include <iostream>
using namespace std;

class Rectangle {
    private:
    float length, breadth;
    
    public:
    Rectangle(float l, float b) {           //Parameterized Constructor
        length = l;
        breadth = b;
    }
    float Area(){
        return length*breadth;
    }
};

int main() {
  Rectangle r(12.64, 7);
  cout<<"Area = "<<r.Area();
  return 0;
}

Output

Area = 88.48

While creating an object in a parameterized constructor, we must pass the initial values as parameters. We can call constructors either explicitly or implicitly.

Explicit call: Rectangle r = Rectangle(12.64, 7);
Implicit call: Rectangle r(12.64, 7);

Uses of parameterized constructor

Using parameterized constructor, we can initialize different objects with different values.
It is used to achieve constructor overloading.

Constructor with Default Arguments

In C++, we can define constructors with default arguments.

Example of constructor with default arguments in C++

#include <iostream>
using namespace std;

class Rectangle {
    private:
    float length, breadth;
    public:
    Rectangle(float l=10, float b=5){       //Constructor with default arguments
        length = l;
        breadth = b;
    }
    void print() {
        cout<<"Length of rectangle = "<<length<<endl;
        cout<<"Breadth of rectangle = "<<breadth<<endl;
    }
};

int main() {
  Rectangle r(20.5);
  r.print();
  return 0;
}

Output

Length of rectangle = 20.5
Breadth of rectangle = 5

3. Copy Constructor in C++

A constructor that initializes an object with the use of another object of the same class is called a copy constructor. It basically copies data of one object to another.

Syntax of a copy constructor

class_name (const class_name &obj) {
  //statements
}

Example of copy constructor in C++

#include <iostream>
using namespace std;

class Square {
    public:
    float side;
    Square(float s) {           
        side = s;
    }
    Square(const Square &obj) {       //Copy Constructor
        side = obj.side;
    }
};

int main() {
  Square s1(4.5);
  Square s2 = s1;     //Copy constructor called
  cout<<"side of 1st square = "<<s1.side<<endl;
  cout<<"side of 2nd square = "<<s2.side;
  return 0;
}

Output

side of 1st square = 4.5
side of 2nd square = 4.5

Remember that

As a best practice, we should define a default constructor if we are defining one or more non-default constructors. This is so because the compiler will not automatically generate a default constructor in this situation. We can also use constructors to execute a default code.

Constructor Overloading in C++

A class in C++ can have many constructors with the same name as long as each has a different set of parameters. Such constructors are called overloaded constructors.

Example of constructor overloading in C++

#include <iostream>
using namespace std;

class Rectangle {
    private:
    float length, breadth;
    public:
    Rectangle() {
        length = 0;
        breadth = 0;
    }
    Rectangle(float l, float b) {
        length = l;
        breadth = b;
    }
    void print() {
        cout<<"Length of rectangle = "<<length<<endl;
        cout<<"Breadth of rectangle = "<<breadth<<endl;
    }
};

int main() {
  Rectangle r1;
  Rectangle r2(20.5, 12);
  r1.print();
  r2.print();
  return 0;
}

Output

Length of rectangle = 0
Breadth of rectangle = 0
Length of rectangle = 20.5
Breadth of rectangle = 12

Destructors in C++

A special member function of a class that destroys or deletes an object is called a destructor.

Syntax:

class_name() {
  //statements
}

A destructor is called when an object is no longer in scope, such as when a function ends, program ends, delete operator is called or a block having local variables ends.

Properties of a destructor in C++

  • When an object is destroyed, it is called automatically.
  • It has the same name as the class.
  • It is preceded by a tilde (~).
  • It does not have any parameters.
  • It has no return type.
  • It cannot be static or const.
  • It must be declared inside public in a class.
  • It’s address is inaccessible to the programmer.

A destructor is useful for freeing resources before exiting a program, such as closing files, releasing memory space, etc.

Example of destructor in C++

#include <iostream>
using namespace std;

class Student {
    private:
    int rollno;
    public:
    Student(){          //constructor
        rollno = 0;
        cout<<"Constructor called"<<endl;
    }
    ~Student(){         //destructor
        cout<<"Destructor called";
    }
};

int main() {
    Student s;
  return 0;
}

Output

Constructor called
Destructor called

Note that

  • We can have only one destructor for a class.
  • If we don’t specify a destructor in the class, the compiler produces a default one for us. However, when we dynamically allocate memory or there is a pointer in the class, we should declare a destructor to prevent memory leaks.

Virtual Destructor in C++

When there is inheritance, we declare the destructor of the base class as virtual. This is so because the non-virtual destructor of the base class has undefined behavior. Making the base class destructor virtual ensures that the derived class objects are properly deleted.

We write this as

virtual ~BaseClassName() {
  //statements
}

Summary

We have learnt constructors and destructors in C++ in this article. These are special member functions of a class.
A constructor is called when an object is created.

There are three types of constructors, default, parameterized and copy constructor. We learnt about all three using examples. We also discussed constructor overloading in C++.

A destructor is called when an object is deleted. We saw an example to better understand a destructor.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.