Constructors and Destructors


what is a constructor in Object oriented language

A constructor is a special function that is a member of the Class and has the same name as that of the Class. Every Object created would have a copy of member data which requires initialization before it can be used. This initialization is common in Object Oriented Language, which allows object to initialize themselves as and when they created. This automatic initialization is performing through the use of constructor functions. The constructor methods exist to simplify the process of initializing class member variables within a class.

Declaration of Constructors

public class Car { int start; public Car() { //Add constructor task here start = 0; } }

A constructor is optional, if no constructors are declared for a class, the compiler invokes a default constructor for you. The default constructor simply sets all the fields in the class to their default values. You can define as many constructors as you want, as long as each constructor has a different parameter list. Also not that constructor functions cannot return values.


what is a destructor in Object oriented language

Destructor is a function that has the same name as that of the class but is prefixed with a ~(tilde). Destructors de-initialize Object when they are destroyed. You can think of destructors as the opposite of constructors: constructors execute when objects are created, and destructors execute when the objects are destroyed by the built in Garbage Collection facility. This process occurs behind the scenes with no consequence to the programmer.

Declaration of Destructors

public class Car { int start; //constructor public Car() { start = 0; } //destructor ~Car() { start = 0; } }

Destructors are optional. Destructors cannot return any values; nor can they accept any parameters. Unlike constructors, you cannot have more than one destructor defined for a class.