Constructor and Destructor in C++

Constructor and Destructor in C++

Let’s see the concept of constructor and destructor in C++.

What is a contructor? Why is it called so?

“A constructor is a special function member of a class. It’s task is to initialize the objects of its class.” It is special because its name is same as that of the class to which it belongs. The constructor is invoked whenever the an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor can never return a value. Hence is written with no return type (not even void is written).

Syntax to declare a constructor –

class class_name
{
     private :
         private_data_members;
     public :
         class_name()  //Constructor
         {
              tasks;
         }
};

Let’s see a short example of constructor to understand better.

class integer
{
    private :
       int m,n;
    public :
       integer();   //declaration of constructor
};

integer :: integer()    //definition of constructor
{
    m = 0;
    n = 0;
}

Whenever a class contains a constructor like one above, the object initializes it automatically as soon as we declare object.
i.e. the declaration : integer int1;
This not only creates the object int1 of type integer, but also initializes its data members m and n to zero.

What is a destructor?

A destructor, as the name implies, is sed to destroy the objects that have been created by a constructor. The compiler invokes destructor implicitly to clean up the storage that is no longer accessible while exiting from the program. In other words, the compiler executes destructor whenever an instance of the class goes out of existence to which it belongs. It is a good practice to declare destructors in a program since it releases memory space for further use.

Let’s see spme syntax rules to declare destructor.

1. A destructor function name is same as that of its class name. But a tilde preceeds the destructor function name.
e.g. ~fib() (…message…..)
2. It has no return data type as it can never return a value.
3. It takes no arguments.
4. It should have public access in the class declaration.

Syntax to declare a destructor –

class class_name
{
     private :
         private_data_members;
     public :
         class_name()  //Constructor
         {
              tasks;
         }
         ~class_name()   //destructor
         {

            ........;
         }
};

Let’s see an example of constructor and destructor.

Q. Write a program in C++ to demostrate constructor & destructor.

1. Program

//Example to demostrate constructor & destructor.

#include<iostream>

using namespace std;

class Demo
{
    public :
        Demo()
        {
            cout<<"\n Object is born";
        }

        void display()
        {
            cout<<"\n Object is Alive";
        }

        ~Demo()
        {
            cout<<"\n Object is Dies";
        }
};

int main()
{
    Demo obj;
    obj.display();
    return 0;
}

2. Output

constructor and destructor in c++

Also Check : What is class? Explain with example.

3. Program Parts

1. #include is a pre-processor directive. It is used to include header files.
2. iostream is header file which has certain commands that c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. class is a keyword to create classes.
5. ~(tilde) is a symbol to declare destructor.
6. int is data type. It indicates that the program returns a value.
7. main() is main function that indicates the compiler that the user written programs starts from here.
8. cout is the keyword use to print a message.
9. cin is the keyword use to store values in variables.
10. return statement is use to return a value. If any error occurs the program will return 0.

4. Explanation

Explanation for this program is very simple. Here we only declare constructor, usere defined function and destructor inside a class (Demo is class name). When we create the object of Demo class the constructor gets invoked automatically. Constructor prints the message “Object is born”. Then we call user defined function display(). It prints the message “Object is alive”. And finally when the main program is completed destructor gets called to destroy the space alloted to Demo class. It prints the message “Object Dies” and program execution terminates.

Conclusion

So this was the concept of constructor & destructor in C++. Hope it was clear to you. If you have any doubt regarding any topic or this concept then just mention it in the comment section. Also if you liked this content then do share it with your programming buddies. Follow us on Instagram for daily updates.

Keep Programming!

ErrorFreeProgram.

Leave a Reply

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