Differentiate between constructor and destructor?
|Subject||Object Oriented Programming|
|NU Year||Set: 2.(c) Marks: 2 Year: 2010 Set: 1.(d) Marks: 5 Year: 2009|
- The main purpose of a constructor is to allocate memory to the objects when they are created whereas, the main purpose of a destructor is to deallocate memory of the object when it is destroyed.
- A constructor is allowed to accept the arguments as the arguments can be used to initialize the data members of the class. A destructor does not accept any arguments as its only work is to deallocate the memory of the object.
- A constructor is called when an object is created. On the other hand, a destructor is called when a program is terminated or the program exit the block in which object is created.
- A constructor is generally used to initialize the data members of the class whereas, a destructor are used to let the object perform some action before it is destroyed.
- Constructors are executed in the successive order that means if there is a derived class that inherits the base class and the object of the derived class is created then it will call the constructor of base class first and then the constructor of derived class. On the other hand, the destructor of derived class is called first and then the base class it means that a destructor is executed in reverse order of constructor.
- In class, there can be multiple constructors which are identified by the number arguments passed. In class, there is only one destructor.
- There is a concept of copy constructor which allows an object to get initialized from an another object whereas, the destructor has no such concept.
- Constructors can be overload to perform different action under the name of the same constructor whereas, destructors can not be overloaded.
Login to post your comment.