Featured Post

ARM- ADC and LCD Interface

In real world all natural quantities like temperature, pressure, light intensity etc. are analog. If we have to deal with such quantities us...

Wednesday 14 August 2019

Constructors & Destructors in C++

Constructors 

A constructor is defined as a 'special' member function, whose work is to initialize  the objects of its class. You might be wondering that why 'special' word is used in the definition of the constructor, well this is because the name of the constructor is same as the class name. The constructor is invoked whenever an object of its associated is created. Another question arises why is it named constructor, well one way to look at this is because it is used to create or construct the value of data member of its class.

Following example will help you understand constructor declaration and definition.



As you can see in the above example , the class name test has a constructor named 'test', it is first declared in the class itself and later defined outside the class using scope resolution operator ( ': :' ) as shown in the above example. Now this constructor will be invoked as soon as an object of class test is created, for example :

test t1 ;                              // constructor invoked.

Constructor can be of the following types :
  • Default Constructor.
  • Parameterized Constructor.
  • Copy Constructor.
  • Dynamic Constructor.

Destructors

Destructors, as the name suggests is something that will destroy something, in this context, destructor is a member function whose function is to destroy the object created by the constructor, like constructor, destructor also have same name as of class name, but it is preceded by a tilde.

In our previous example, if we want to destroy the object created by constructor 'test' , following has to be done.

~test( ){ }                        // Destructor declaration.

At the end of the program, all the test objects will be destroyed, always remember that a destructor never takes any argument nor returns any value, henceforth it will be invoked implicitly by the compiler when the program ends.

It is a good habbit to declare a destructor in your program as it will release memory space for future use.Whenever new operator is used to allocate memory in any program, in order to delete that space, we use delete operator, for example.



The primary use of destructor is in freeing up of memory reserved by the object before it gets destroyed.

No comments:

Post a Comment