Difference Between Constructor and Destructor

Server Side ProgrammingProgrammingComputer Engineering

In this post, we will understand the difference between constructor and destructor.

Constructor

  • It helps allocate memory to an object.

  • It can take arguments.

  • It is called automatically when an object is created.

  • It allows an object to initialize a value before it is used.

  • They are called in the successive order of their creation.

  • There can be multiple constructors in a single class.

  • The copy constructor allows the constructor to declare and initialize an object from another object.

  • It can be overloaded.

Example:

class_name( arguments if any )
{
};

Destructor

  • It deallocates the memory of an object.

  • It doesn’t take any argument.

  • It is called automatically when the block is exited or when the program terminates.

  • They allow objects to execute code when it is being destroyed.

  • They are called in the reverse order of their creation.

  • There is a single destructor in a class.

  • Destructor can’t be overloaded.

Example:

~ class_name( no arguments )
{
};
raja
Published on 25-Mar-2021 05:33:44
Advertisements