ProAnswers.org

What is the difference between constructor and destructor in C++?

4 Likes

the main difference is that constructor constructs the values of an object and aA destructor destructs the values created by the constructor for the object.

  • A constructor is called when you want to create a new instance of a class. A destructor is called when you want to free up the memory of an object (when you delete it).

  • A constructor constructs the value of an object . A destructor destructs the value created by the constructor for the object.

    Another differentiation is their syntax’s :

constructor :

(Arguments)

{

//body of constructor.

}

destructor :

~()

{

}

** constructor IS CALLED IN THE BEGINNING OF THE PROGRAMM AND **DESTRUCTOR IS CALLED AT THE ENDING OF THE PROGRAM.

**CONSTRUCTER CAN BE OVERLOADED
**DESTROCTER CN NOT BE OVERLOADED

Constructor:

  • Constructor is Used to Initialize the Object.

  • Constructor can takes arguments.

  • Constructor overloading can be possible means more than one constructors can be defined in same class.

  • Constructor has same name as class name.

  • Syntax of constructor:

    class class_name
    {
    clas_sname(){}
    class_name(argulist){}
    };

  • Constructor are of following:

    1. Default Constructor.
    2. Parameterized Constructor.
    3. Copy Constructor.
  • Constructors can be used to dynamically initialize the memory.

  • Constructor indirectly use the New operator to initialize the object.

Destructor:

  • Destructor is used to destroy the object that are created in memory previously.

  • Destructor can not take any arguments.

  • Destructor overloading can not be possible.

  • Destructor has same name as class name with tiled operator.

  • Syntax of Destructor:

    class class_name
    {
    ~class-name(void){}
    };

  • Destructor has no any types.

  • Destructor can be used to de-allocate the memory.

  • Destructor indirectly use the Delete operator to destroy the object initialize by constructor.

it really help me and nice
thank u :slight_smile:

very simple and important answers !! thnks a lot !

thanks!!! very simple Nd easy explanation.

really nice explanation n to the point…

Thank for the difference but can you please tell what are the similarities between them?

Thank’s for this. it is really very helpful…

Both have the name of the class .
Both have no return type.
References and pointers cannot be used in constructors and destructors

Its a very2 good explanation thanks for your write difference between i am very appreciate to u sir