Constructors and Destructors

Constructors :

  • Constructors are called whenever an object for a class is created.
  • They are generally used for initializing the objects of a class.
  • They are like functions but ,they have same name as that of class and have no return type(not even void).
    class_name()
    {
    ……….
    }
  • Like functions they can also be defined outside the class using :: operator.
    class_name::class_name()
    {
    ……….
    }
  • There are three types of constructors :
  1. Simple constructor
  2. Parameterized constructor
  3. Copy constructor

Parameterized constructors :

  • Which can accept argument or parameters.
  • They are to initialize the values at the time of object creation.

Syntax :  

class_name(data_type param1, data_type param2,…) 
       {
        ………. 
       }

Copy constructor :

They are used to :

  • To create an object with same initial values as other.
  • To copy an object to pass it to a function or return it from a function.
  • If a copy constructor is not defined in a class, the compiler itself defines one.
  • If the class has pointer variables and has some dynamic memory allocations, then it must have a copy constructor.

Constructor Overloading :

  • Like functions, constructors can also be overloaded i.e. one class can have more than one constructor.
  • This can be by defining constructors of different types or with different signatures(no. of parameters ).

Destructors :

  • A destructor is just the opposite of a constructor, called at the time destroying the objects for freeing memory and relinquish resources held by object.
  • A destructor must has same name as that of the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters.

Syntax :   
~class_name() 
       { 
        ………. 
       }

Note : Constructors and destructors are only called once for an object in a program.

e.g.

OUTPUT :

 

Leave a Reply

Your email address will not be published. Required fields are marked *